﻿namespace SheetLib
{
    using IOLib;
    //using NuLib;
    using System.Linq;
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.IO;
    using System.Runtime.CompilerServices;
    using System.Text;
    using System.Threading;
    using System.Windows.Forms;
    using System.Xml;
    using System.Drawing.Drawing2D;

    public class SheetControl : Control
    {
        /*
        
        
        
        
        public Hashtable canvasInfo;
        
        private ErrorControl currentError;
        private Size currenterror_size = new Size();
        
        private System.Windows.Forms.Timer errordisplay_timer;
        private int errortimer_inc = 1;
        private Evaluation eval;
        public DateTime evalEnd;
        public DateTime evalStart;
        public Thread evalThread;
        
        
        
        private string hash;
        
        private bool intoApplyTag;
        
        private Collection<CustomLine> linesToDraw;
        
        private int selStatus;
        private string smartChar;
        private System.Windows.Forms.Timer smartDec;
        private string smartIndex;
        private System.Windows.Forms.Timer smartTimer;
        private Brush sur_brush;
        private Brush sur_brushB;
        private Brush sur_brushG;
        private Brush sur_brushR;
        private Brush sur_brushY;
        private Random sur_random;
        private System.Windows.Forms.Timer sur_timer;
        private int sur_y;
        private ArrayList surprise;
        
        
        private Collection<UnReDO_Canvas> UnReDO;
        private int unReDoPoint;
        private UnReDoStatus unReDoStatus;
        private string uri1 = "http://schemas.mathsoft.com/worksheet30";
        private string uri2 = "http://schemas.mathsoft.com/math30";
        

        */

        private Bitmap _bmp;
        private Graphics _graphics;
        public string backFile;
        private Brush brush_control;
        private List<BaseControl> cacheControls;//Collection<CommonControl> cacheControls;
        private bool cacheStatus;
        private CursorStatus currentCursor;
        /// <summary>
        /// Коллекция элементов, содержащихся на листе.
        /// </summary>
        private List<BaseControl> controls; // CommonControlsArrayList controls;
        public int ctrlSize;
        /// <summary>
        /// коллекция соединителей на листе.
        /// </summary>
        private List<Connector> connectors;
        private Connector connEntered;
        /// <summary>
        /// Коолекция областей, подходящих для начала либо окончания (зависит от текущей надобности отображения) соединителя,
        /// находящихся непосредственно под указателем миши.
        /// </summary>
        private List<HotSpot> connHotSpots;
        /// <summary>
        /// Область, выбранная для начала соединителя.
        /// </summary>
        private HotSpot startHS;
        private ClipboardStatus clipboardStatus;
        private Rectangle curElt;
        /// <summary>
        /// Индекс текущего елемента листа.
        /// </summary>
        private int current;
        private int currentDelta;
        private int currentPos;
        private bool drawAll;
        /// <summary>
        /// true, если нужно прорисовывать сетку, иначе false.
        /// </summary>
        public bool drawGrid;
        /// <summary>
        /// true, если лист содержит несохраненные изменения, иначе false.
        /// </summary>
        private int edited;
        private bool flag;
        private SheetStatus fullPageStatus;//CanvasStatus fullPageStatus;
        /// <summary>
        /// Колличество пикселей равное периоду дискретизации движения красного крестика(указателя)
        /// </summary>
        public int gridSize;
        public string homeFile;
        private bool IsPickedUp;
        public string localpath;
        /// <summary>
        /// true, если одна из кнопок миши находится в нажатом состоянии, иначе false.
        /// </summary>
        private bool mousedown;
        /// <summary>
        /// Координаты, в которых произошло нажатие миши, приведенное к дискретизованым положениям левого верхнего угла указателя
        /// </summary>
        private Point mousePlace;
        /// <summary>
        /// Координата
        /// </summary>
        private Point mousePos;
        private Rectangle newConnRect;
        public CanvasEditStatus pageState;
        private Pen pen_black;
        private Pen pen_gray;
        private Pen pen_grid;
        private Pen pen_redcross;
        private Pen pen_dash;
        /// <summary>
        /// Координаты центра крассного крестика (указателя).
        /// </summary>
        private Point pt; 
        /// <summary>
        /// X, Y - Координаты центра крассного крестика (указателя) относительно видемой области;
        /// Width, Height - определяются положением указателя миши при выделении эллементов квадратом
        /// </summary>
        private Rectangle rc;//SMathDecision.RECT rc;
        private bool redcrossvisible;
        private Color selColor;
        private Rectangle[] selected;//SMathDecision.RECT[] selected;
        private List<Rectangle> selCtrls;
        private System.Windows.Forms.Timer select2focusTimer;
        /// <summary>
        /// Индексы выделенных елементов.
        /// </summary>
        private List<int> selected_controls;
        private int[] selected_controls_ctrl;
        public string selfFile;
        private Point temp;
        public string[] title;
        private Point vid1;
        private Point vid2;
        private Brush whiteBrush;
        private int xBar;
        public HScrollBar Xbar;
        private int xBarMax;
        private int xBarWidth;
        /// <summary>
        /// X - координата точки нажатия миши в координатах листа
        /// </summary>
        private int xPos;
        private int yBar;
        public VScrollBar Ybar;
        private int yBarHeight;
        private int yBarMax;
        /// <summary>
        /// Y - координата точки нажатия миши в координатах листа
        /// </summary>
        private int yPos;
        //private int UnReDoMaximum;


        public delegate void OnPageStatusChanged(SheetControl sender, SheetStatus status);
        public event OnPageStatusChanged onPageStatusChanged;

        public SheetControl()
        {
            this.InitializeComponent();
            //this.canvasInfo = new Hashtable();
            this.redcrossvisible = false;
            this.selColor = Color.FromArgb(0, 120, 200);
            this.curElt = new Rectangle();
            //this.surprise = new ArrayList();
            this.whiteBrush = new SolidBrush(Color.White);
            this.currentCursor = new CursorStatus(-1, CursorType.Arrow);
            this.selected_controls_ctrl = new int[0];
            this.selCtrls = new List<Rectangle>();
            //this.linesToDraw = new Collection<CustomLine>();
            //this.smartTimer = new System.Windows.Forms.Timer();
            //this.smartTimer.Interval = 0x3e8;
            //this.smartTimer.Tick += new EventHandler(this.smartTimer_Tick);
            //this.smartDec = new System.Windows.Forms.Timer();
            //this.smartDec.Interval = 400;
            //this.smartDec.Tick += new EventHandler(this.smartDec_Tick);
            this.edited = -1;
            //this.UnReDoMaximum = this.UnReDoPoint = -1;
            //this.UnReDO = new Collection<UnReDO_Canvas>();
            //this.eval = new Evaluation();
            //this.eval.onEval += new EvalAction(this.Evaluation_onEval);
            this.drawAll = false;
        }

        private int AreaCommonDelta(BaseControl control)
        {
            int num = 0;
            int num2 = 0;
            int y = -1;
            int count = this.controls.Count;
            while (num2 < count)
            {
                if (control == this.controls[num2])
                {
                    return num;
                }
                /*if (this.controls[num2] is AreaControl)
                {
                    AreaControl control2 = (AreaControl) this.controls[num2];
                    if ((y != -1) && !control2.top)
                    {
                        num += control2.Location.Y - y;
                        y = -1;
                    }
                    else if (control2.top && control2.collapsed)
                    {
                        y = control2.Location.Y;
                    }
                }*/
                num2++;
            }
            return num;
        }

        private void CanvasResizer()
        {
            int x = 0;
            int y = 0;
            for (int i = this.controls.Count - 1; i >= 0; i--)
            {
                if ((this.controls[i].Right + 5) > x)
                {
                    x = this.controls[i].Right + 5;
                }
                if ((this.controls[i].Bottom + 5) > y)
                {
                    y = this.controls[i].Bottom + 5;
                }
            }
            if (this.current == -1)
            {
                if (this.MousePlace.X > x)
                {
                    x = this.MousePlace.X;
                }
                if (this.MousePlace.Y > y)
                {
                    y = this.MousePlace.Y;
                }
            }
            this.DoSetXBARUpdate(x + ((this.pageState == CanvasEditStatus.ReadOnly) ? 0 : this.xBarWidth));
            this.DoSetYBARUpdate(y + ((this.pageState == CanvasEditStatus.ReadOnly) ? 0 : this.yBarHeight));
        }

        private void CanvasResizer(BaseControl value)
        {
            if (this.pageState == CanvasEditStatus.ReadOnly)
            {
                if (this.xBarMax < (value.Right + 5))
                {
                    this.DoSetXBARUpdate(value.Right + 5);
                }
                if (this.yBarMax < (value.Bottom + 5))
                {
                    this.DoSetYBARUpdate(value.Bottom + 5);
                }
            }
            else
            {
                if ((this.xBarMax - this.xBarWidth) < (value.Right + 5))
                {
                    this.DoSetXBARUpdate((value.Right + this.xBarWidth) + 5);
                }
                if ((this.yBarMax - this.yBarHeight) < (value.Bottom + 5))
                {
                    this.DoSetYBARUpdate((value.Bottom + this.yBarHeight) + 5);
                }
            }
        }

        public bool ClipboardGetData()
        {
            try
            {
                IDataObject dataObject = Clipboard.GetDataObject();
                if (dataObject.GetDataPresent("MemoryStream"))
                {
                    if (this.selected_controls.Count > 0)
                    {
                        for (int i = this.selected_controls.Count - 1; i >= 0; i--)
                        {
                            this.controls[this.selected_controls[i]].Selected = false;
                        }
                    }
                    MemoryStream data = (MemoryStream) dataObject.GetData("MemoryStream");
                    this.OpenXML(data, false);
                    data.Flush();
                    this.SelectControls(SelectionType.Testing);
                    return true;
                }
            }
            catch
            {
            }
            return false;
        }

        public Bitmap ClipboardGetImage()
        {
            try
            {
                IDataObject dataObject = Clipboard.GetDataObject();
                if (dataObject.GetDataPresent(DataFormats.Bitmap))
                {
                    return (Bitmap) dataObject.GetData(DataFormats.Bitmap);
                }
            }
            catch
            {
            }
            return null;
        }

        public string ClipboardGetText()
        {
            try
            {
                IDataObject dataObject = Clipboard.GetDataObject();
                if (dataObject.GetDataPresent(DataFormats.UnicodeText))
                {
                    return (string) dataObject.GetData(DataFormats.UnicodeText);
                }
            }
            catch
            {
            }
            return null;
        }

        public void ClipboardSetData()
        {
            MemoryStream stream = new MemoryStream();
            this.SaveToXML(stream, false);
            stream.Position = 0;
            IDataObject text = new DataObject();
            text.SetData("MemoryStream", stream);
            this.ClipboardSetObject(text);
            stream.Flush();
        }

        public void ClipboardSetObject(object text)
        {
            if (text != null)
            {
                Clipboard.SetDataObject(text);
                this.clipboardStatus = ClipboardStatus.HasData;
            }
        }

        private string Color2String(int value)
        {
            Color color = Color.FromArgb(value);
            string str = color.R.ToString("x");
            string str2 = color.G.ToString("x");
            string str3 = color.B.ToString("x");
            return ("#" + ((str == "0") ? "00" : str) + ((str2 == "0") ? "00" : str2) + ((str3 == "0") ? "00" : str3));
        }

        /*private void ContinueHistory(UnReDoType type)
        {
            this.cacheStatus = false;
            if ((this.cacheControls != null) && (this.cacheControls.Count > 0))
            {
                this.UndoRedoManager(this.cacheControls.ToArray(), type, -1);
            }
            this.cacheControls = null;
        }*/

        private void control_drawCustomLine(PaintEventArgs e, Pen pen, int x1, int y1, int x2, int y2)
        {
            //this.linesToDraw.Add(new CustomLine(pen.Color, 1, x1, y1, x2, y2));
        }

        private BaseControl ControlCopy(BaseControl value)
        {
            //if (value is MathControl)
            //{
            //    return new MathControl((MathControl) value);
            //}
            if (value is TextControl)
            {
                return new TextControl((TextControl) value);
            }
            if (value is BlockControl)
            {
            }
            //if (value is PlotControl)
            //{
            //    return new PlotControl((PlotControl) value);
            //}
            //if (value is AreaControl)
            //{
            //    return new AreaControl((AreaControl) value);
            //}
            if (value is PictureControl)
            {
                return new PictureControl((PictureControl) value);
            }
            return new BaseControl();
        }

        private void ControlPaint(BaseControl control, PaintEventArgs args)
        {
            try
            {
                control.OnPaint(args);
            }
            catch (Exception exception)
            {
                MessageBox.Show(string.Concat(new object[] { Error.CriticalError, "\n", exception.Message, "\n", Error.ControlCanNotBeDisplayed }));
                this.controls.Remove(control);
                this.current = -1;
                base.Invalidate();
            }
        }

        private void ControlUnfocus()
        {
            if (this.current != -1)
            {
                BaseControl control = this.controls[this.current];
                this.current = -1;
                control.Focused = false;
                control.RePainter();
                this.MousePlace = new Point(this.Grider(control.Location.X), this.Grider(control.Location.Y + control.Size.Height));
                base.Invalidate(new Rectangle(this.MousePlace.X - this.Xbar.Value, this.MousePlace.Y - this.Ybar.Value, this.gridSize, this.gridSize));
                this.CanvasResizer();
                //this.ErrorHide();
            }
        }

        private XmlAttribute CreateXMLAttribute(string name, string value, XmlDocument doc, XmlNode node)
        {
            XmlAttribute attribute = doc.CreateAttribute(name);
            attribute.Value = value;
            node.Attributes.Append(attribute);
            return attribute;
        }

        private void DeleteRedCross()
        {
            if (!GlobalParams.ctrlKeyPressed && this.selected_controls.Count > 0)
            {
                this.SelectControls(SelectionType.None);
            }
            if (this.redcrossvisible)
            {
                base.Invalidate(new Rectangle(this.MousePlace.X - this.Xbar.Value, this.MousePlace.Y - this.Ybar.Value, this.gridSize, this.gridSize));
            }
        }

        /*public void DoErrorDisplay(string text, Point Location, bool IsNew)
        {
            if (this.InvokeRequired)
            {
                ShowCalculationError method = new ShowCalculationError(this.DoErrorDisplay);
                base.Invoke(method, new object[] { text, Location, IsNew });
            }
            else
            {
                Location.X -= this.xBar;
                Location.Y -= this.yBar;
                this.currentError.Location = Location;
                this.currentError.Text = text;
                if (IsNew)
                {
                    this.errordisplay_timer.Enabled = true;
                    this.errortimer_inc = 1;
                    this.currenterror_size = new Size(this.currentError.Size.Width, this.currentError.Size.Height);
                    this.currentError.Size = new Size((int) (this.currenterror_size.Width * 0.1), (int) (this.currenterror_size.Height * 0.1));
                }
                this.currentError.Visible = true;
            }
        }*/

        private void DoINeedToDeleteElement(int controlIndex)
        {
            if (this.controls != null && this.controls.Count > controlIndex && /*((((this.controls[controlIndex] is MathControl) && (((MathControl) this.controls[controlIndex]).IMG.Length == 1)) && ((((MathControl) this.controls[controlIndex]).IMG[0].Text == "#") && (((MathControl) this.controls[controlIndex]).IMG[0].Type == EquType.Operand))) ||*/ 
                ((this.controls[controlIndex] is TextControl &&
                  ((TextControl)this.controls[controlIndex]).Text == "")||
                 this.controls[controlIndex].needToDelete) /*) && (!(this.controls[controlIndex] is TextControl) || !((TextControl) this.controls[controlIndex]).RemoveText())*/)
            {
                this.RemoveControls(new int[] { controlIndex });
            }
        }

        /*public void DoPrepareError(Exception e, CommonControl sender, EquImage[] ei, ParamWizard param, CalculateType value)
        {
            if (this.InvokeRequired)
            {
                DelegateDoPrepareError method = new DelegateDoPrepareError(this.DoPrepareError);
                base.Invoke(method, new object[] { e, sender, ei, param, value });
            }
            else if (sender is MathControl)
            {
                MathControl control = (MathControl) sender;
                control.InDate = true;
                control.InEvaluation = false;
                if (e is ThreadAbortException)
                {
                    control.ErrorText = SSException.GetErrorText(Error.ProcessingInterruptedByUser);
                    control.errorId = Error.ProcessingInterruptedByUser;
                    if (control.Focused)
                    {
                        this.DoErrorDisplay(control.ErrorText, new Point(control.Location.X + 2, control.Bottom), true);
                    }
                }
                else
                {
                    control.ErrorText = e.Message;
                    control.errorId = SSException.GetErrorId(e);
                    if (e.InnerException != null)
                    {
                        if ((((value == CalculateType.Numeric) && control.Focused) && ((ei[ei.Length - 1].Type == EquType.Function) || ((ei.Length == 1) && (ei[ei.Length - 1].Type == EquType.Operand)))) && (!this.eval.ParamContainsElement(param, ei[ei.Length - 1]) && ((ei[ei.Length - 1].Type == EquType.Operand) || ((ei[ei.Length - 1].Type == EquType.Function) && !Function.Contains(ei[ei.Length - 1].Text)))))
                        {
                            control.IMG = ei;
                            control.watch = new int[] { control.IMG.Length - 1, control.IMG[control.IMG.Length - 1].Text.Length - 1 };
                            control.Action("←");
                            control.ErrorText = "";
                            return;
                        }
                        int position = Convert.ToInt32(e.InnerException.Message);
                        if ((ei != null) && (ei.Length > position))
                        {
                            control.dec_errorprovider_nu(e, position, ei[position]);
                        }
                    }
                    if (control.Focused)
                    {
                        control.InDate = true;
                        this.DoErrorDisplay(e.Message, new Point(control.Location.X + 2, control.Bottom), true);
                    }
                }
                control.Action(ei, new EquImage[] { new EquImage("#", EquType.Operand, 0) }, value);
            }
        }*/

        public void DoSetCANVASUpdate(Rectangle rect)
        {
            if (this.InvokeRequired)
            {
                base.Invoke(new SheetGUI(this.DoSetCANVASUpdate), rect );
            }
            else
            {
                base.Invalidate(rect);
            }
        }

        public void DoSetXBARUpdate(int max)
        {
            if (this.InvokeRequired)
            {
                base.Invoke(new BarGUI(this.DoSetXBARUpdate), max );
            }
            else
            {
                this.Xbar.Maximum = max;
                this.xBarMax = max;
            }
        }

        public void DoSetYBARUpdate(int max)
        {
            if (this.InvokeRequired)
            {
                base.Invoke(new BarGUI(this.DoSetYBARUpdate), max );
            }
            else
            {
                this.Ybar.Maximum = max;
                this.yBarMax = max;
            }
        }

        private int ElementCreater(BaseControl control, Point location, bool addToPage, bool postProcessing, bool makeCurrent, bool addToHistory)
        {
            control.Location = location;
            //control.errorprovider += new SheetLib.ErrorProvider(this.v_errorprovider);
            //control.CalculateMe += new CalculateAction(this.v_CalculateMe);
            control.Repainting += new BaseControl.ControlPaintEventHandler(control_Repainting);
            control.OnResize += new BaseControl.ControlEventHandler(control_OnResize);
            //control.OnLinkClick += new CommonAction(this.v_OnLinkClick);
            //control.historyChanged += new HistoryChanged(this.v_history);
            //control.drawCustomLine += new NeedToDrawCustomLine(this.control_drawCustomLine);
            //control.onShowError += new ShowCalculationErrorEval(this.DoPrepareError);
            //control.onShowResult += new ShowCalculationResultEval(this.Evaluation_onShowResult);
            //control.setControlEvaluationState += new SetControlEvaluationState(this.SetEvaluation_onShowResult);
            int num = -1;
            if (addToPage)
            {
                this.controls.Add(control);
                num = this.controls.Count-1;
                this.CanvasResizer();
            }
            if (postProcessing)
            {
                this.controls.Sort(delegate(BaseControl a, BaseControl b) {
                                            if ((a.Location.Y < b.Location.Y) ||
                                                ((a.Location.Y == b.Location.Y) && (a.Location.X < b.Location.X)))
                                                 return -1;
                                            else return 1;});
                num = -1;
            }
            if (makeCurrent)
            {
                num = this.current = this.controls.IndexOf(control);
                this.DeleteRedCross();
                control.Focus();
            }
            if (addToHistory)
            {
                //this.UndoRedoManager(control, UnReDoType.ControlAdd, this.current);
            }
            return num;
        }

        /*private void errordisplay_timer_Tick(object sender, EventArgs e)
        {
            this.currentError.Size = new Size((int) (this.currenterror_size.Width * (((double) this.errortimer_inc) / 10.0)), (int) (this.currenterror_size.Height * (((double) this.errortimer_inc) / 10.0)));
            this.currentError.Invalidate();
            this.errortimer_inc++;
            if (this.errortimer_inc == 11)
            {
                this.errordisplay_timer.Enabled = false;
            }
        }*/

        /*private void ErrorHide()
        {
            if (this.currentError.Visible)
            {
                this.currentError.Visible = false;
            }
        }*/

        /*private void Evaluation_onEval(string action)
        {
            this.evalThread = null;
            this.SetEvalEndValue(DateTime.Now);
            this.pageState = CanvasEditStatus.Editable;
            this.PageStatusManager();
        }*/

        /*private void Evaluation_onShowResult(CommonControl sender, EquImage[] ei, EquImage[] tstr2, CalculateType value)
        {
            if (this.InvokeRequired)
            {
                DoEvaluationOnShowResult method = new DoEvaluationOnShowResult(this.Evaluation_onShowResult);
                base.Invoke(method, new object[] { sender, ei, tstr2, value });
            }
            else if (sender is MathControl)
            {
                MathControl control = (MathControl) sender;
                control.Action(ei, tstr2, value);
                control.InDate = true;
            }
        }*/

        public void ExportHTML(string fileName)
        {
            FileStream stream = null;
            StreamWriter writer = null;
            /*try
            {
                Cursor.Current = Cursors.WaitCursor;
                stream = File.Open(fileName, FileMode.Create, FileAccess.Write);
                writer = new StreamWriter(stream);
                if (stream != null)
                {
                    string[] strArray = fileName.Split(new char[] { Path.DirectorySeparatorChar });
                    string str = strArray[strArray.Length - 1].Remove(strArray[strArray.Length - 1].Length - 4, 4);
                    string path = string.Concat(new object[] { fileName.Remove(fileName.Length - (4 + str.Length), 4 + str.Length), Path.DirectorySeparatorChar, str, Path.DirectorySeparatorChar });
                    Directory.CreateDirectory(path);
                    writer.WriteLine("<html><head><title>" + str + "</title><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"><meta name=Generator content=\"" + LangSelection.FTitle + "\"><meta name=ProgID content=\"" + LangSelection.FTitle + "\"></head><body>");
                    for (int i = this.controls.Count - 1; i >= 0; i--)
                    {
                        string str3 = str + "_" + i.ToString() + ".png";
                        string filename = path + str3;
                        if (this.controls[i] is MathControl)
                        {
                            this.controls[i].GetImage().Save(filename, ImageFormat.Png);
                            writer.WriteLine("<div style=\"position:absolute;left:" + Convert.ToString((int) (this.controls[i].Location.X + 4)) + ";top:" + Convert.ToString((int) (this.controls[i].Location.Y + 4)) + "\"><img src=\"" + str + "/" + str3 + "\" /></div>");
                        }
                        else if (this.controls[i] is PlotControl)
                        {
                            this.controls[i].GetImage().Save(filename, ImageFormat.Png);
                            writer.WriteLine("<div style=\"position:absolute;left:" + Convert.ToString((int) (this.controls[i].Location.X + 4)) + ";top:" + Convert.ToString((int) (this.controls[i].Location.Y + 4)) + "\"><img src=\"" + str + "/" + str3 + "\" /></div>");
                        }
                        else if (this.controls[i] is PictureControl)
                        {
                            ((PictureControl) this.controls[i]).ExportImage().Save(filename, ImageFormat.Png);
                            writer.WriteLine("<div style=\"position:absolute;left:" + Convert.ToString((int) (this.controls[i].Location.X + 4)) + ";top:" + Convert.ToString((int) (this.controls[i].Location.Y + 4)) + "\"><img src=\"" + str + "/" + str3 + "\" /></div>");
                        }
                        else if (this.controls[i] is TextControl)
                        {
                            writer.WriteLine(string.Concat(new object[] { "<div style=\"position:absolute;left:", Convert.ToString((int) (this.controls[i].Location.X + 4)), ";top:", Convert.ToString((int) (this.controls[i].Location.Y + 4)), ";width:", this.controls[i].Size.Width, "\"><font face=\"Courier New,Courier,mono\" style=\"font-size:", this.controls[i].FontHeight, "pt;background-color:", this.Color2String(this.controls[i].BackColor.ToArgb()), ";font-family:\"Courier New\",Courier,mono;\" color=\"", this.Color2String(this.controls[i].TextColor.ToArgb()), "\">", ((TextControl) this.controls[i]).Text.Replace("\r", " <BR>"), "</font></div>" }));
                        }
                    }
                    writer.WriteLine("</body></html>");
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show(Error.ExportError + " " + exception.Message);
            }
            finally
            {
                if (writer != null)
                {
                    writer.Flush();
                }
                if (stream != null)
                {
                    stream.Close();
                }
                Cursor.Current = Cursors.Default;
            }*/
        }

        public CursorStatus GetCursorType(MouseEventArgs e)
        {
            bool flag = GlobalParams.ctrlKeyPressed && this.IsPickedUp;
            if ((!this.flag && this.mousedown) && (this.IsPickedUp || (this.selected_controls.Count > 0)))
            {
                this.currentCursor.CursorType = flag ? CursorType.MovingAdd : CursorType.Moving;
            }
            if (e.Button == MouseButtons.Left)
            {
                if (flag && (this.currentCursor.CursorType == CursorType.Move))
                {
                    this.currentCursor.CursorType = CursorType.MovingAdd;
                }
                else if (!GlobalParams.ctrlKeyPressed && (this.currentCursor.CursorType == CursorType.MovingAdd))
                {
                    this.currentCursor.CursorType = CursorType.Move;
                }
                return this.currentCursor;
            }
            if ((e.X > this.SheetSize.Width) || (e.Y > this.SheetSize.Height))
            {
                this.currentCursor.CursorType = CursorType.Arrow;
            }
            else
            {
                this.currentCursor.CursorType = CursorType.Arrow;
                bool flag2 = false;
                int count = this.controls.Count;
                for(int i=0;i<this.controls.Count;i++)
                {
                    BaseControl control = this.controls[i];
                    if (control.Location.Y - this.Ybar.Value > e.Y)
                    {
                        break;
                    }
                    if ((control.Location.X - this.Xbar.Value <= e.X) &&
                        (control.Right - this.Xbar.Value >= e.X) &&
                        (control.Location.Y - this.Ybar.Value <= e.Y) &&
                        (control.Bottom - this.Ybar.Value >= e.Y))
                    {
                        this.currentCursor.Control = i;
                        flag2 = true;
                        if (control.Focused || control.Selected)
                        {
                            if (control.Selected ||
                                (control.Location.X - this.Xbar.Value + 5 > e.X) ||
                                (control.Right - this.Xbar.Value - 5 < e.X) ||
                                (control.Location.Y - this.Ybar.Value + 5 > e.Y) ||
                                (control.Bottom - this.Ybar.Value - 5 < e.Y))
                            {
                                this.currentCursor.CursorType = flag ? CursorType.MovingAdd : CursorType.Move;
                            }
                            else
                            {
                                this.currentCursor.CursorType = control.GetCursorType(
                                    new MouseEventArgs(e.Button, 0, e.X - control.Location.X + this.Xbar.Value - 4,
                                        e.Y - control.Location.Y + this.Ybar.Value - 4, 0));
                            }
                            break;
                        }
                    }
                }
                if (!flag2)
                {
                    this.currentCursor.Control = -1;
                }
            }
            return this.currentCursor;
        }

        /*public CtrlsEvalutionState GetEvalutionState()
        {
            if (this.selected_controls.Count > 0)
            {
                for (int i = this.selected_controls.Count - 1; i >= 0; i--)
                {
                    if (this.controls[this.selected_controls[i]] is MathControl)
                    {
                        if (!((MathControl) this.controls[this.selected_controls[i]]).Evaluate)
                        {
                            return CtrlsEvalutionState.Disabled;
                        }
                        return CtrlsEvalutionState.Evaluate;
                    }
                    if (this.controls[this.selected_controls[i]] is PlotControl)
                    {
                        if (!((PlotControl) this.controls[this.selected_controls[i]]).Evaluate)
                        {
                            return CtrlsEvalutionState.Disabled;
                        }
                        return CtrlsEvalutionState.Evaluate;
                    }
                    if ((this.controls[this.selected_controls[i]] is AreaControl) && ((AreaControl) this.controls[this.selected_controls[i]]).top)
                    {
                        if (!((AreaControl) this.controls[this.selected_controls[i]]).Evaluate)
                        {
                            return CtrlsEvalutionState.Disabled;
                        }
                        return CtrlsEvalutionState.Evaluate;
                    }
                }
            }
            else if (this.current != -1)
            {
                if (this.controls[this.current] is MathControl)
                {
                    if (!((MathControl) this.controls[this.current]).Evaluate)
                    {
                        return CtrlsEvalutionState.Disabled;
                    }
                    return CtrlsEvalutionState.Evaluate;
                }
                if (this.controls[this.current] is PlotControl)
                {
                    if (!((PlotControl) this.controls[this.current]).Evaluate)
                    {
                        return CtrlsEvalutionState.Disabled;
                    }
                    return CtrlsEvalutionState.Evaluate;
                }
                if ((this.controls[this.current] is AreaControl) && ((AreaControl) this.controls[this.current]).top)
                {
                    if (!((AreaControl) this.controls[this.current]).Evaluate)
                    {
                        return CtrlsEvalutionState.Disabled;
                    }
                    return CtrlsEvalutionState.Evaluate;
                }
            }
            return CtrlsEvalutionState.NotSupported;
        }*/

        private SheetStatus GetPageStatus()
        {
            //CanvasSelectionStatus none = CanvasSelectionStatus.None;
            //CtrlInSelection inCtrlSelection = CtrlInSelection.None;
            //ControlType controlType = ControlType.None;
            /*if (this.selected_controls.Count > 0)
            {
                none = CanvasSelectionStatus.Selected;
            }
            else if (this.current != -1)
            {
                none = CanvasSelectionStatus.InEdit;
            }
            if (((this.current >= 0) && (this.controls != null)) && (this.current < this.controls.Count))
            {
                if ((this.controls[this.current] is MathControl) || (this.controls[this.current] is PlotControl))
                {
                    EquImage[] selectedItems = ((this.controls[this.current] is MathControl) ? ((MathControl) this.controls[this.current]) : ((PlotControl) this.controls[this.current]).math).GetSelectedItems();
                    if (selectedItems != null)
                    {
                        if (selectedItems.Length == 1)
                        {
                            inCtrlSelection = MathMethods.IsNumber(selectedItems[0].Text) ? CtrlInSelection.Constant : CtrlInSelection.Variable;
                        }
                        else
                        {
                            inCtrlSelection = CtrlInSelection.MathExpression;
                        }
                    }
                }
                else if (this.controls[this.current] is TextControl)
                {
                    string str = ((TextControl) this.controls[this.current]).GetSelectedItems();
                    if ((str != null) && (str.Length > 0))
                    {
                        inCtrlSelection = CtrlInSelection.Text;
                    }
                }
                if (this.controls[this.current] is MathControl)
                {
                    controlType = ControlType.Math;
                }
                else if (this.controls[this.current] is PlotControl)
                {
                    controlType = ControlType.Plot;
                }
                else if (this.controls[this.current] is TextControl)
                {
                    controlType = ControlType.Text;
                }
                else if (this.controls[this.current] is PictureControl)
                {
                    controlType = ControlType.Picture;
                }
                else if (this.controls[this.current] is AreaControl)
                {
                    controlType = ControlType.Area;
                }
            }*/
            return new SheetStatus(this.pageState, /*none, inCtrlSelection,*/ this.clipboardStatus, /*this.unReDoStatus, this.GetEvalutionState(),*/ this.Edited/*, controlType*/);
        }

        private int Grider(int value)
        {
            return ((value / this.gridSize) * this.gridSize);
        }

        private void GridPainting(ref Graphics _graphics, Rectangle e)
        {
            int num = this.gridSize * 2;
            int num2 = ((this.Ybar.Value / this.gridSize) % 2) * this.gridSize;
            int num3 = ((this.Xbar.Value / this.gridSize) % 2) * this.gridSize;
            int num4 = (((int) (((double) e.Height) / ((double) num))) + 1) * num;
            int num5 = (((int) (((double) e.Width) / ((double) num))) + 1) * num;
            int num6 = (e.Y / num) * num;
            int num7 = (e.X / num) * num;
            int num8 = num6 + num2;
            num4 += num8;
            while (num8 <= num4)
            {
                if ((num8 >= 0) && (e.Bottom >= num8))
                {
                    _graphics.DrawLine(this.pen_grid, e.X, num8, e.Right, num8);
                }
                num8 += num;
            }
            num8 = num7 + num3;
            num5 += num8;
            while (num8 <= num5)
            {
                if ((num8 >= 0) && (e.Right >= num8))
                {
                    _graphics.DrawLine(this.pen_grid, num8, e.Y, num8, e.Bottom);
                }
                num8 += num;
            }
        }

        private void InitializeComponent()
        {
            //this.smartChar = "1";
            //this.smartIndex = "1";
            this.rc = new Rectangle();
            this.gridSize = GlobalParams.gridSize;
            this.ctrlSize = (int) GlobalParams.ScreenResolutionFactor;
            this.brush_control = new SolidBrush(SystemColors.Control);
            this.pen_grid = new Pen(Color.FromArgb(230, 230, 230));
            this.pen_redcross = new Pen(Color.Red);
            this.pen_black = new Pen(Color.Black);
            this.pen_gray = new Pen(Color.Gray);
            this.pen_dash = new Pen(new HatchBrush(HatchStyle.WideDownwardDiagonal, Color.White));
            this.selected_controls = new List<int>();
            this.title = new string[] { string.Empty, string.Empty };
            this.localpath = GlobalParams.ApplicationPath;
            this.selfFile = "";
            this.homeFile = "";
            this.backFile = "";
            this.mousedown = false;
            this.IsPickedUp = false;
            this.drawGrid = true;
            this.current = -1;
            this.xBar = 0;
            this.yBar = 0;
            this.xBarMax = 0;
            this.yBarMax = 0;
            this.MousePlace = new Point(0, 0);
            this.controls = new List<BaseControl>();
            this.connectors = new List<Connector>();
            this.connHotSpots = new List<HotSpot>();
            this.select2focusTimer = new System.Windows.Forms.Timer();
            this.Xbar = new HScrollBar();
            this.Ybar = new VScrollBar();
            this.Xbar.ValueChanged += new EventHandler(this.ScrollBars_ValueChanged);
            this.Ybar.ValueChanged += new EventHandler(this.ScrollBars_ValueChanged);
            base.Size = new Size(100, 50);
            base.Controls.Add(this.Xbar);
            base.Controls.Add(this.Ybar);
            this.select2focusTimer.Interval = 150;
            this.select2focusTimer.Tick += new EventHandler(this.select2focusTimer_Tick);
            this.select2focusTimer.Enabled = false;
            //this.currentError = new ErrorControl();
            //this.currentError.Visible = false;
            //base.Controls.Add(this.currentError);
            //this.errordisplay_timer = new System.Windows.Forms.Timer();
            //this.errordisplay_timer.Interval = 10;
            //this.errordisplay_timer.Tick += new EventHandler(this.errordisplay_timer_Tick);
            //this.sur_timer = new System.Windows.Forms.Timer();
            //this.sur_timer.Interval = 50;
            //this.sur_timer.Tick += new EventHandler(this.sur_timer_Tick);
            //this.sur_timer.Enabled = false;
        }

        public void Insert(string value)
        {
            try
            {
                this.ParseInsertString(value);
            }
            finally
            {
                this.PageStatusManager();
            }
        }

        private void LinkOpener(string fileName)
        {
            if (!Path.IsPathRooted(fileName))
            {
                fileName = this.localpath + fileName;
            }
            if (!File.Exists(fileName))
            {
                MessageBox.Show(SSException.GetErrorText(Error.CanNotFindFile) + fileName, GlobalParams.FTitle);
            }
            else
            {
                this.current = -1;
                this.controls.Clear();
                base.Invalidate();
                this.Xbar.Value = 0;
                this.Ybar.Value = 0;
                Cursor.Current = Cursors.WaitCursor;
                this.OpenXML(fileName, true);
                Cursor.Current = Cursors.Default;
            }
        }

        /*private static EquImage[] MergeManyArrayPostfix(EquImage[][] value, int ind, int amount)
        {
            int num = 1;
            for (int i = 1; i <= amount; i++)
            {
                if (value[ind - i] != null)
                {
                    num += value[ind - i].Length;
                }
            }
            int num3 = 0;
            EquImage[] imageArray = new EquImage[num3 + num];
            for (int j = 1; j <= amount; j++)
            {
                if (value[ind - j] != null)
                {
                    for (int k = 0; k < value[ind - j].Length; k++)
                    {
                        imageArray[k + num3] = value[ind - j][k];
                    }
                    num3 += value[ind - j].Length;
                }
            }
            return imageArray;
        }*/

        /*private static EquImage[] MergeManyArrayPrefix(EquImage[][] value, int ind, int amount)
        {
            int num = 0;
            for (int i = 1; i <= amount; i++)
            {
                if (value[ind - i] != null)
                {
                    num += value[ind - i].Length;
                }
            }
            int num3 = 1;
            EquImage[] imageArray = new EquImage[num3 + num];
            for (int j = amount; j > 0; j--)
            {
                if (value[ind - j] != null)
                {
                    for (int k = 0; k < value[ind - j].Length; k++)
                    {
                        imageArray[k + num3] = value[ind - j][k];
                    }
                    num3 += value[ind - j].Length;
                }
            }
            return imageArray;
        }*/

        private void MoveControlForMouseUp(int j, int commonDelta, ref bool NeedFullReCalc)
        {
            BaseControl control = this.controls[this.selected_controls[j]];
            /*if (!NeedFullReCalc && Evaluation.DoINeedToBeRecalculated(control, Evaluation.EquCheckType.EqualsAndDefinitions))
            {
                NeedFullReCalc = true;
            }
            if (control is AreaControl)
            {
                control.Location = new Point(this.Xbar.Value, this.Grider(((this.selected[j].Top + commonDelta) + this.Ybar.Value) + 2));
            }
            else*/
            {
                control.Location = new Point(this.Grider((this.selected[j].Left + this.Xbar.Value) + 2), this.Grider(((this.selected[j].Top + commonDelta) + this.Ybar.Value) + 2));
            }
        }

        protected override void OnGotFocus(EventArgs e)
        {
            try
            {
                IDataObject dataObject = Clipboard.GetDataObject();
                if ((dataObject.GetDataPresent("MemoryStream") || dataObject.GetDataPresent(DataFormats.UnicodeText)) || dataObject.GetDataPresent(DataFormats.Bitmap))
                {
                    this.clipboardStatus = ClipboardStatus.HasData;
                }
                else
                {
                    this.clipboardStatus = ClipboardStatus.Empty;
                }
            }
            catch
            {
            }
            GlobalParams.ctrlKeyPressed = false;
            GlobalParams.shiftKeyPressed = false;
            this.PageStatusManager();
        }

        protected override void OnKeyDown(KeyEventArgs e)
        {
            GlobalParams.ctrlKeyPressed = e.Control;
            GlobalParams.shiftKeyPressed = e.Shift;
            if (e.KeyData == (Keys.Control | Keys.Shift | Keys.P))
            {
                this.Insert('π'.ToString());
            }
            else if (e.KeyData == (Keys.Control | Keys.Shift | Keys.Z))
            {
                this.Insert("∞");
            }
            else if (e.Control && (e.KeyValue == 190))
            {
                this.Insert("—");
            }
            else if (e.KeyData == (Keys.Control | Keys.D3))
            {
                this.Insert("≠");
            }
            else if (e.KeyData == (Keys.Control | Keys.D8))
            {
                this.Insert("†");
            }
            else if (e.KeyData == (Keys.Control | Keys.D9))
            {
                this.Insert("≤");
            }
            else if (e.KeyData == (Keys.Control | Keys.D0))
            {
                this.Insert("≥");
            }
            else if ((e.KeyCode == Keys.Oemplus) && e.Control)
            {
                this.Insert("≡");
            }
            else if (e.KeyData == (Keys.Control | Keys.T))
            {
                this.Insert("INSERTPICTURE");
            }
            else if (e.KeyData == (Keys.Control | Keys.Z))
            {
                this.Insert("UNDO");
            }
            else if (e.KeyData == (Keys.Control | Keys.Y))
            {
                this.Insert("REDO");
            }
            else if (e.KeyData == (Keys.Control | Keys.X))
            {
                this.Insert("CUT");
            }
            else if (e.KeyData == (Keys.Control | Keys.C))
            {
                this.Insert("COPY");
            }
            else if (e.KeyData == (Keys.Control | Keys.V))
            {
                this.Insert("PASTE");
            }
            else if (e.KeyData == (Keys.Control | Keys.A))
            {
                this.Insert("SELECTALL");
            }
            else if (e.KeyData == (Keys.Control | Keys.G))
            {
                this.Insert("TOGREEK");
            }
            else if ((e.KeyData == (Keys.Control | Keys.Return)) || (e.KeyData == (Keys.Shift | Keys.Return)))
            {
                this.Insert("\r");
            }
            else if (e.KeyData == Keys.Prior)
            {
                this.Insert("PAGEUP");
            }
            else if (e.KeyData == Keys.Next)
            {
                this.Insert("PAGEDOWN");
            }
            else if (e.KeyData == Keys.Home)
            {
                this.Insert("HOME");
            }
            else if (e.KeyData == Keys.End)
            {
                this.Insert("END");
            }
            /*else if (LangSelection.Platform == LangSelection.PlatformType.Smartphone)
            {
                if (e.KeyValue == 0x77)
                {
                    if (this.selStatus == 0)
                    {
                        this.selStatus = 1;
                    }
                }
                else if (e.KeyValue == 120)
                {
                    this.smartDec.Enabled = true;
                }
            }*/
            base.OnKeyDown(e);
        }

        protected override void OnKeyPress(KeyPressEventArgs e)
        {
            /*if ((LangSelection.Platform == LangSelection.PlatformType.Smartphone) && (e.KeyChar == '\x001b'))
            {
                this.Insert("\b");
                e.Handled = true;
            }
            else*/ 
            if (((!GlobalParams.ctrlKeyPressed && (e.KeyChar != '\x001c')) && ((e.KeyChar != '\t') && (e.KeyChar != '\x0010'))) && (!GlobalParams.shiftKeyPressed || (e.KeyChar != '\r')))
            {
                /*if (((LangSelection.Platform == LangSelection.PlatformType.Smartphone) && (e.KeyChar == '\r')) && (this.selStatus > 0))
                {
                    this.selStatus = 2;
                }*/
                this.Insert(e.KeyChar.ToString());
            }
            base.OnKeyPress(e);
        }

        protected override void OnKeyUp(KeyEventArgs e)
        {
            GlobalParams.ctrlKeyPressed = e.Control;
            GlobalParams.shiftKeyPressed = e.Shift;
            base.OnKeyUp(e);
        }

        protected override void OnMouseDown(MouseEventArgs e)
        {
            base.OnMouseDown(e);
            this.Focus();
            if (this.mousedown)
            {
                this.OnMouseUp(e);
            }
            //if (this.sur_timer.Enabled)
            // {
            //     this.sur_timer.Enabled = false;
            //     base.Invalidate();
            // }
            if (e.Button != MouseButtons.Left)
            {
                this.PageStatusManager();
                return;
            }
            int current = this.current;
            bool flag = (this.current != -1) ? this.controls[this.current].Focused : false;
            this.mousedown = true;
            e = new MouseEventArgs(e.Button, 1, e.X + this.Xbar.Value, e.Y + this.Ybar.Value, 0);
            this.xPos = e.X;
            this.yPos = e.Y;
            bool needSetStartHsNull = true;
            foreach (HotSpot hs in connHotSpots)
            {
                if (hs.Area.IsVisible(e.Location))
                {
                    if (startHS == null)
                    {
                        startHS = hs;
                        needSetStartHsNull = false;
                    }
                    else if (startHS != hs)
                    {
                        connectors.Add(new Connector(startHS, hs, this));

                        //

                        BlockControl src = startHS.Control as BlockControl;
                        BlockControl dst = hs.Control as BlockControl;

                        if (src != null && dst != null)
                        {
                            src.MathModel.OutputBlocks.Add(new Matan.ConnectedBlock(dst.MathModel, startHS.ConnectionPlace));
                            dst.MathModel.InputBlocks.Add(new Matan.ConnectedBlock(src.MathModel, hs.ConnectionPlace));                            
                        }

                        //

                        connectors[connectors.Count - 1].Repainting += new Connector.ConnectorPaintEventHandler(connector_Repainting);
                        connectors[connectors.Count - 1].Connect();
                        startHS = null;
                        Rectangle rect = Rectangle.Ceiling(hs.Area.GetBounds());
                        rect.X -= this.Xbar.Value;
                        rect.Y -= this.Ybar.Value;
                        rect.Inflate(1, 1);
                        if (newConnRect != null) rect = Rectangle.Union(rect, newConnRect);
                        this.Invalidate(rect);
                    }
                    this.mousedown = false;
                    return;
                }
            }
            if (needSetStartHsNull)
            {
                startHS = null;
                if (newConnRect != Rectangle.Empty)
                {
                    this.Invalidate(newConnRect);
                    newConnRect = Rectangle.Empty;
                }
            }
            if (this.current != -1 && this.controls[this.current].Focused &&
                this.selected_controls.Count == 0 && this.curElt.Left <= e.X - 3 &&
                this.curElt.Right >= e.X + 3 && this.curElt.Top <= e.Y + this.currentDelta - 3 &&
                this.curElt.Bottom >= e.Y + this.currentDelta + 3 &&
                this.curElt.X == this.controls[this.current].Location.X + 2 &&
                this.curElt.Y == this.controls[this.current].Location.Y + 2 &&
                this.curElt.Width == this.controls[this.current].Size.Width - 4 &&
                this.curElt.Height == this.controls[this.current].Size.Height - 4)
            {
                BaseControl control = this.controls[this.current];
                if (GlobalParams.ctrlKeyPressed)
                {
                    if (control.Focused)
                    {
                        control.Focused = false;
                    }
                    return;
                }
                control.OnMouseDown(new MouseEventArgs(e.Button, 1, (e.X - control.Location.X) - 4, (e.Y - (control.Location.Y - this.currentDelta)) - 4, 0));
            }
            else
            {
                this.current = -1;
                for (int i = 0; i < this.controls.Count; i++)
                {
                    BaseControl control2 = this.controls[i];
                    int num6 = 0;
                    if (!control2.Focused && !control2.Selected)
                    {
                        num6 = 5;
                    }
                    if (this.current == -1 && e.X >= control2.Location.X + num6 &&
                        e.X <= control2.Right - num6 && e.Y >= control2.Location.Y + num6 &&
                        e.Y <= control2.Bottom - num6)
                    {
                        if (((current != -1) && (current != i)) && flag)
                        {
                            this.controls[current].Focused = false;
                            this.controls[current].RePainter();
                            //this.ErrorHide();
                        }
                        this.current = i;
                        this.currentDelta = 0;
                    }
                    if (this.current == i)
                    {
                        if (GlobalParams.ctrlKeyPressed)
                        {
                            if (control2.Focused)
                            {
                                control2.Focused = false;
                            }
                            return;
                        }
                        if (control2.Selected)
                        {
                            this.select2focusTimer.Enabled = true;
                            this.IsPickedUp = true;
                            this.PreSelect(control2, new Point(e.X, e.Y));
                            this.pt = new Point(e.X - this.Xbar.Value, e.Y - this.Ybar.Value);
                        }
                        else
                        {
                            //if (((current != -1) && !this.controls[current].InDate) && ((current != this.current) && Evaluation.DoINeedToBeRecalculated(this.controls[current], Evaluation.EquCheckType.EqualsAndDefinitions)))
                            //{
                            //    this.ReCalc(current);
                            //}
                            if (e.X <= control2.Location.X + 4 || e.X >= control2.Right - 4 ||
                                e.Y <= control2.Location.Y + 4 || e.Y >= control2.Bottom - 4)
                            {
                                control2.Focused = true;
                                this.IsPickedUp = true;
                                this.selected = new Rectangle[] { new Rectangle() };
                                this.selected[0].X = control2.Location.X - this.Xbar.Value + 2;
                                this.selected[0].Width = control2.Right - control2.Location.X - 4;
                                this.selected[0].Y = control2.Location.Y - this.Ybar.Value + 2;
                                this.selected[0].Height = control2.Bottom - control2.Location.Y - 4;
                                this.vid1 = new Point((e.X - this.selected[0].Left) - this.Xbar.Value, e.Y - this.selected[0].Top - this.Ybar.Value);
                                this.vid2 = new Point(e.X - control2.Location.X, e.Y - control2.Location.Y);
                            }
                            else
                            {
                                control2.OnMouseDown(new MouseEventArgs(e.Button, 1,
                                    e.X - control2.Location.X - 4, e.Y - control2.Location.Y - 4, 0));
                            }
                            this.DeleteRedCross();
                        }
                    }
                    else if (control2.Focused)
                    {
                        control2.Focused = false;
                        control2.RePainter();
                    }
                }
            }
            if (this.current == -1)
            {
                /*this.ErrorHide();
                if (((current != -1) && !this.controls[current].InDate) && Evaluation.DoINeedToBeRecalculated(this.controls[current], Evaluation.EquCheckType.EqualsAndDefinitions))
                {
                    this.ReCalc(current);
                }*/
                this.DeleteRedCross();
                this.MousePlace = new Point(this.Grider(e.X), this.Grider(e.Y));
                /*if (this.surprise.Count != 0)
                {
                    Point point17 = (Point) this.surprise[this.surprise.Count - 1];
                    if ((point17.X + this.gridSize) != this.MousePlace.X)
                    {
                        goto Label_0845;
                    }
                    Point point19 = (Point) this.surprise[this.surprise.Count - 1];
                    if ((point19.Y + this.gridSize) != this.MousePlace.Y)
                    {
                        goto Label_0845;
                    }
                }
                this.surprise.Add(new Point(this.MousePlace.X, this.MousePlace.Y));
                if (this.surprise.Count == 5)
                {
                    base.Invalidate();
                    this.sur_timer.Enabled = true;
                }
                goto Label_0850;
            Label_0845:
                this.surprise.Clear();
            Label_0850:*/
                this.flag = true;
                this.rc.X = (this.MousePlace.X - this.Xbar.Value) + ((this.gridSize - 1) / 2);
                this.rc.Y = (this.MousePlace.Y - this.Ybar.Value) + ((this.gridSize - 1) / 2);
                this.rc.Width = 0;
                this.rc.Height = 0;
                this.pt = new Point(this.MousePlace.X + ((this.gridSize - 1) / 2), this.MousePlace.Y + ((this.gridSize - 1) / 2));
                this.CanvasResizer();
                if (GlobalParams.ctrlKeyPressed)
                {
                    this.selected_controls_ctrl = this.selected_controls.ToArray();
                }
                else
                {
                    this.selected_controls_ctrl = new int[0];
                }
                base.Invalidate(new Rectangle(this.MousePlace.X - this.Xbar.Value, this.MousePlace.Y - this.Ybar.Value, this.gridSize, this.gridSize));
            }
            if (current != -1 && this.controls[current] is TextControl &&
                ((TextControl)this.controls[current]).Text == "" && !this.controls[current].Focused)//&& !((TextControl) this.controls[current]).RemoveText())
            {
                this.controls.RemoveAt(current);
            }
            if (connEntered != null && connEntered.ConnectorArea.IsVisible(e.Location))
            {
                if (GlobalParams.ctrlKeyPressed)
                {
                    connEntered.Selected = !connEntered.Selected;
                }
                else
                {
                    bool one = true;
                    Rectangle rect;
                    for (int i = 0; i < connectors.Count; i++)
                    {
                        if (connectors[i].Selected && connectors[i] != connEntered)
                        {
                            connectors[i].Selected = one = false;
                            rect = Rectangle.Ceiling(connectors[i].ConnectorArea.GetBounds());
                            rect.X -= this.Xbar.Value;
                            rect.Y -= this.Ybar.Value;
                            rect.Inflate(1, 1);
                            this.Invalidate(rect);
                        }
                    }
                    connEntered.Selected = !one || !connEntered.Selected;
                }
            }
            else
            {
                Rectangle rect;
                for (int i = 0; i < connectors.Count; i++)
                {
                    if (connectors[i].Selected)
                    {
                        connectors[i].Selected = false;
                        rect = Rectangle.Ceiling(connectors[i].ConnectorArea.GetBounds());
                        rect.X -= this.Xbar.Value;
                        rect.Y -= this.Ybar.Value;
                        rect.Inflate(1, 1);
                        this.Invalidate(rect);
                    }
                }
            }
            this.PageStatusManager();
        }

        protected override void OnMouseMove(MouseEventArgs e)
        {
            base.OnMouseMove(e);
            e = new MouseEventArgs(e.Button, 1, e.X + this.Xbar.Value, e.Y + this.Ybar.Value, 0);
            if (this.mousedown && ((this.xPos != e.X) || (this.yPos != e.Y)))
            {
                if (this.IsPickedUp && (this.pageState == CanvasEditStatus.Editable))
                {
                    if (((e.X - this.Xbar.Value) < ((this.gridSize - 1) / 2)) && (this.Xbar.Value >= this.Xbar.SmallChange))
                    {
                        this.Xbar.Value -= this.Xbar.SmallChange;
                    }
                    if (((e.X - this.Xbar.Value) > (this.SheetSize.Width - ((this.gridSize - 1) / 2))) && (this.Xbar.Value <= ((this.Xbar.Maximum - this.Xbar.Width) - this.Xbar.SmallChange)))
                    {
                        this.Xbar.Value += this.Xbar.SmallChange;
                    }
                    if (((e.Y - this.Ybar.Value) < ((this.gridSize - 1) / 2)) && (this.Ybar.Value >= this.Ybar.SmallChange))
                    {
                        this.Ybar.Value -= this.Ybar.SmallChange;
                    }
                    if (((e.Y - this.Ybar.Value) > (this.SheetSize.Height - ((this.gridSize - 1) / 2))) && (this.Ybar.Value <= ((this.Ybar.Maximum - this.Ybar.Height) - this.Ybar.SmallChange)))
                    {
                        this.Ybar.Value += this.Ybar.SmallChange;
                    }
                    if (((e.X - this.vid2.X) >= 0) && (((e.X - this.vid2.X) + this.Xbar.Value) <= int.MaxValue))
                    {
                        this.temp.X = (e.X - this.vid1.X) - this.Xbar.Value;
                    }
                    else
                    {
                        this.temp.X = (this.vid2.X - this.vid1.X) - this.Xbar.Value;
                    }
                    if (((e.Y - this.vid2.Y) >= 0) && (((e.Y - this.vid2.Y) + this.Ybar.Value) <= int.MaxValue))
                    {
                        this.temp.Y = (e.Y - this.vid1.Y) - this.Ybar.Value;
                    }
                    else
                    {
                        this.temp.Y = (this.vid2.Y - this.vid1.Y) - this.Ybar.Value;
                    }
                    int index = 0;
                    int length = this.selected.Length;
                    while (index < length)
                    {
                        base.Invalidate(this.selected[index]);
                        int num3 = this.selected[index].Right - this.selected[index].Left;
                        int num4 = this.selected[index].Bottom - this.selected[index].Top;
                        this.selected[index].X = this.temp.X - (this.selected[length - 1].Left - this.selected[index].Left);
                        this.selected[index].Width = this.selected[index].Left + num3 - this.selected[index].Left;
                        this.selected[index].Y = this.temp.Y - (this.selected[length - 1].Top - this.selected[index].Top);
                        this.selected[index].Height = this.selected[index].Top + num4 - this.selected[index].Top;
                        base.Invalidate(this.selected[index]);
                        index++;
                    }
                }
                else if (this.current != -1)
                {
                    BaseControl control = this.controls[this.current];
                    if (GlobalParams.ctrlKeyPressed)
                    {
                        control.Selected = true;
                        this.SelectControls(SelectionType.Testing);
                        this.PreSelect(control, new Point(e.X, e.Y));
                        this.IsPickedUp = true;
                        base.Invalidate(new Rectangle(this.MousePlace.X - this.Xbar.Value, this.MousePlace.Y - this.Ybar.Value, this.gridSize, this.gridSize));
                    }
                    else if (this.selected_controls.Count == 0)
                    {
                        control.OnMouseMove(new MouseEventArgs(e.Button, 1, e.X - control.Location.X - 4, e.Y - control.Location.Y - this.currentDelta - 4, 0));
                    }
                }
                else if (this.flag)
                {
                    Rectangle rectangle = new Rectangle(rc.Location, rc.Size);
                    if (((e.X - this.Xbar.Value) < ((this.gridSize - 1) / 2)) && (this.Xbar.Value >= this.Xbar.SmallChange))
                    {
                        this.Xbar.Value -= this.Xbar.SmallChange;
                    }
                    if (((e.X - this.Xbar.Value) > (this.SheetSize.Width - ((this.gridSize - 1) / 2))) && (this.Xbar.Value <= ((this.Xbar.Maximum - this.Xbar.Width) - this.Xbar.SmallChange)))
                    {
                        this.Xbar.Value += this.Xbar.SmallChange;
                    }
                    if (((e.Y - this.Ybar.Value) < ((this.gridSize - 1) / 2)) && (this.Ybar.Value >= this.Ybar.SmallChange))
                    {
                        this.Ybar.Value -= this.Ybar.SmallChange;
                    }
                    if (((e.Y - this.Ybar.Value) > (this.SheetSize.Height - ((this.gridSize - 1) / 2))) && (this.Ybar.Value <= ((this.Ybar.Maximum - this.Ybar.Height) - this.Ybar.SmallChange)))
                    {
                        this.Ybar.Value += this.Ybar.SmallChange;
                    }
                    if ((this.pt.X - this.Xbar.Value) > (e.X - this.Xbar.Value))
                    {
                        this.rc.X = e.X - this.Xbar.Value;
                        this.rc.Width = (this.pt.X - e.X) + 1;
                    }
                    else
                    {
                        this.rc.X = this.pt.X - this.Xbar.Value;
                        this.rc.Width = e.X - this.pt.X;
                    }
                    if ((this.pt.Y - this.Ybar.Value) > (e.Y - this.Ybar.Value))
                    {
                        this.rc.Y = e.Y - this.Ybar.Value;
                        this.rc.Height = (this.pt.Y - e.Y) + 1;
                    }
                    else
                    {
                        this.rc.Y = this.pt.Y - this.Ybar.Value;
                        this.rc.Height = e.Y - this.pt.Y;
                    }
                    this.SelectControls(SelectionType.ByRectangle);
                    int x = Math.Min(this.rc.Left, rectangle.Left);
                    int y = Math.Min(this.rc.Top, rectangle.Top);
                    base.Invalidate(new Rectangle(x, y, Math.Max((int)(this.rc.Right - this.rc.Left), (int)(rectangle.Right - x)), Math.Max((int)(this.rc.Bottom - this.rc.Top), (int)(rectangle.Bottom - y))));
                }
                this.xPos = e.X;
                this.yPos = e.Y;
            }
            else if(!mousedown)
            {
                Rectangle rect;
                HotSpot[] oldHSs = connHotSpots.ToArray();
                this.connHotSpots.Clear();
                //GraphicsPath gp1 = new GraphicsPath();
                //gp1.AddLine(1, 1, 2, 2);
                //GraphicsPath gp2 = new GraphicsPath();
                //gp2.AddLine(1, 1, 2, 2);
                //MessageBox.Show((gp1.GetBounds() == gp2.GetBounds() && gp1.PointCount == gp2.PointCount).ToString());
                for (int i = 0; i < this.controls.Count; i++)
                {
                    foreach (HotSpot hs in this.controls[i].GetConnHotSpots(startHS==null))
                    {
                        if (hs.Area.IsVisible(e.Location))
                        {
                            this.connHotSpots.Add(hs);
                            rect = Rectangle.Ceiling(hs.Area.GetBounds());
                            rect.X -= this.Xbar.Value;
                            rect.Y -= this.Ybar.Value;
                            rect.Inflate(1, 1);
                            this.Invalidate(rect);
                            break;
                        }
                    }
                }
                foreach (HotSpot hs in oldHSs)
                {
                    if (!this.connHotSpots.Contains(hs))
                    {
                        rect = Rectangle.Ceiling(hs.Area.GetBounds());
                        rect.X -= this.Xbar.Value;
                        rect.Y -= this.Ybar.Value;
                        rect.Inflate(1, 1);
                        this.Invalidate(rect);
                    }
                }
                if (startHS != null)
                {
                    mousePos = e.Location;
                    Point first = ((ConnectedElement)startHS).ConnectionPoint;
                    rect = new Rectangle(Math.Min(first.X, e.X), Math.Min(first.Y, e.Y),
                        Math.Abs(first.X - e.X)+1, Math.Abs(first.Y - e.Y)+1);
                    if (newConnRect != null) rect = Rectangle.Union(rect, newConnRect);
                    newConnRect = rect;
                    this.Invalidate(rect);
                    return;
                }
                foreach (Connector c in connectors)
                {
                    if (c.ConnectorArea.IsVisible(e.Location))
                    {
                        connEntered = c;
                        rect = Rectangle.Ceiling(c.ConnectorArea.GetBounds());
                        rect.X -= this.Xbar.Value;
                        rect.Y -= this.Ybar.Value;
                        rect.Inflate(1, 1);
                        this.Invalidate(rect);
                        return;
                    }
                }
                if (connEntered != null)
                {
                    rect = Rectangle.Ceiling(connEntered.ConnectorArea.GetBounds());
                    rect.X -= this.Xbar.Value;
                    rect.Y -= this.Ybar.Value;
                    rect.Inflate(1, 1);
                    connEntered = null;
                    this.Invalidate(rect);
                }
            }
        }

        protected override void OnMouseUp(MouseEventArgs e)
        {
            if ((e.Button == MouseButtons.Left) || (e.Button == MouseButtons.Middle))
            {
                this.mousedown = false;
                if (this.IsPickedUp)
                {
                    int count = this.selected_controls.Count;
                    if ((this.select2focusTimer.Enabled && (e.X == this.pt.X)) && (e.Y == this.pt.Y))
                    {
                        this.select2focusTimer.Enabled = false;
                        for (int i = this.selected_controls.Count - 1; i >= 0; i--)
                        {
                            this.controls[this.selected_controls[i]].Selected = false;
                        }
                        this.selected_controls.Clear();
                        this.IsPickedUp = false;
                        this.OnMouseDown(new MouseEventArgs(e.Button, 1, this.xPos - this.Xbar.Value, this.yPos - this.Ybar.Value, 0));
                        this.OnMouseUp(new MouseEventArgs(e.Button, 1, this.xPos - this.Xbar.Value, this.yPos - this.Ybar.Value, 0));
                        this.DeleteRedCross();
                    }
                    else if (count != 0)
                    {
                        this.StartCacheHistory();
                        /*if (LangSelection.ctrlKeyPressed)
                        {
                            bool flag = false;
                            CommonControl control = null;
                            for (int j = count - 1; j >= 0; j--)
                            {
                                control = this.ControlCopy(this.controls[this.selected_controls[j]]);
                                control.Selected = true;
                                this.controls[this.selected_controls[j]].Selected = false;
                                this.ElementCreater(control, new Point(this.Grider((this.selected[j].Left + this.Xbar.Value) + 2), this.Grider((this.selected[j].Top + this.Ybar.Value) + 2)), true, false, false, true);
                                base.Invalidate(new Rectangle(this.selected[j].Left, this.selected[j].Top, this.selected[j].Right - this.selected[j].Left, this.selected[j].Bottom - this.selected[j].Top));
                                control.RePainter();
                                if (!flag && Evaluation.DoINeedToBeRecalculated(control, Evaluation.EquCheckType.EqualsAndDefinitions))
                                {
                                    flag = true;
                                }
                            }
                            this.controls.Sort();
                            if (flag)
                            {
                                this.ReCalc(this.controls.IndexOf(control));
                            }
                            this.SelectControls(SelectionType.Testing);
                            this.ContinueHistory(UnReDoType.ControlAdd);
                        }
                        else*/
                        {
                            this.StartLocationChanging();
                            bool needFullReCalc = false;
                            int index = 0;
                            int commonDelta = 0;
                            BaseControl start = this.controls[this.selected_controls[0]];
                            int num6 = 0;
                            int y = -1;
                            int num8 = this.controls.Count;
                            while ((num6 < num8) && (index < count))
                            {
                                BaseControl control3 = this.controls[num6];
                                if (!control3.Selected && ((this.Grider(this.selected[index].Top) < ((control3.Location.Y - commonDelta) - this.Ybar.Value)) || ((this.Grider(this.selected[index].Top) == ((control3.Location.Y - commonDelta) - this.Ybar.Value)) && (this.Grider(this.selected[index].Left) < (control3.Location.X - this.Xbar.Value)))))
                                {
                                    this.MoveControlForMouseUp(index++, commonDelta, ref needFullReCalc);
                                    num6--;
                                }
                                num6++;
                            }
                            while (index < count)
                            {
                                this.MoveControlForMouseUp(index++, commonDelta, ref needFullReCalc);
                            }
                            this.CanvasResizer(this.controls[this.selected_controls[count - 1]]);
                            //this.StopLocationChanging(needFullReCalc, start, this.selected_controls[0]);
                            this.SelectControls(SelectionType.Testing);
                            //this.ContinueHistory(UnReDoType.Control);
                            base.Invalidate();
                        }
                        this.current = -1;
                    }
                    else if (GlobalParams.ctrlKeyPressed)
                    {
                        BaseControl control5 = this.ControlCopy(this.controls[this.current]);
                        this.controls[this.current].Focused = false;
                        this.controls[this.current].RePainter();
                        this.ElementCreater(control5, new Point(this.Grider((this.selected[0].Left + this.Xbar.Value) + 2), this.Grider((this.selected[0].Top + this.Ybar.Value) + 2)), true, true, true, true);
                        base.Invalidate(new Rectangle(this.selected[0].Left, this.selected[0].Top, this.selected[0].Right - this.selected[0].Left, this.selected[0].Bottom - this.selected[0].Top));
                        control5.RePainter();
                        //if (Evaluation.DoINeedToBeRecalculated(control5, Evaluation.EquCheckType.EqualsAndDefinitions))
                        //{
                        //    this.ReCalc(this.current);
                        //}
                    }
                    else
                    {
                        this.StartLocationChanging();
                        BaseControl control6 = this.controls[this.current];
                        if ((control6.Location.X != this.Grider((this.selected[0].Left + this.Xbar.Value) + 2)) || ((control6.Location.Y - this.currentDelta) != this.Grider((this.selected[0].Top + this.Ybar.Value) + 2)))
                        {
                            Rectangle rect = Rectangle.Empty;
                            for (int i = 0; i < control6.AssociatedConnectors.Length; i++)
                            {
                                if (control6.AssociatedConnectors[i] != null)
                                {
                                    for (int j = 0; j < control6.AssociatedConnectors[i].Count; j++)
                                    {
                                        rect = Rectangle.Union(rect,
                                            control6.AssociatedConnectors[i][j].ClipRectangle);
                                    }
                                }
                            }
                            /*if (control6 is AreaControl)
                            {
                                control6.Location = new Point(this.Xbar.Value, this.Grider((this.selected[0].Top + this.Ybar.Value) + 2));
                            }
                            else*/
                            {
                                control6.Location = new Point(this.Grider((this.selected[0].Left + this.Xbar.Value) + 2), this.Grider(((this.selected[0].Top + this.currentDelta) + this.Ybar.Value) + 2));
                            }
                            //this.StopLocationChanging(Evaluation.DoINeedToBeRecalculated(control6, Evaluation.EquCheckType.EqualsAndDefinitions), control6, this.current);
                            this.current = this.controls.IndexOf(control6);
                            this.CanvasResizer(this.controls[this.current]);
                            for (int i = 0; i < control6.AssociatedConnectors.Length; i++)
                            {
                                if(control6.AssociatedConnectors[i]!=null)
                                {
                                    for (int j = 0; j < control6.AssociatedConnectors[i].Count; j++)
                                    {
                                        rect = Rectangle.Union(rect,
                                            control6.AssociatedConnectors[i][j].ClipRectangle);
                                    }
                                }
                            }
                            base.Invalidate(rect);
                        }
                        base.Invalidate(new Rectangle(this.selected[0].Left, this.selected[0].Top - this.currentDelta, this.selected[0].Right - this.selected[0].Left, (this.selected[0].Bottom - this.selected[0].Top) + this.currentDelta));
                    }
                    this.IsPickedUp = false;
                }
                else if (this.flag)
                {
                    this.flag = false;
                    base.Invalidate(new Rectangle(this.rc.Left, this.rc.Top, this.rc.Right - this.rc.Left, this.rc.Bottom - this.rc.Top));
                }
                else if (this.current != -1)
                {
                    if (GlobalParams.ctrlKeyPressed)
                    {
                        this.controls[this.current].Selected = !this.controls[this.current].Selected;
                        this.SelectControls(SelectionType.Testing);
                        this.current = -1;
                        base.Invalidate(new Rectangle(this.MousePlace.X - this.Xbar.Value, this.MousePlace.Y - this.Ybar.Value, this.gridSize, this.gridSize));
                    }
                    else
                    {
                        this.controls[this.current].OnMouseUp(e);
                    }
                }
            }
            this.PageStatusManager();
        }

        public void OnMouseWheel(Point pnt, int wheel)
        {
            if (((pnt.Y >= (base.Height - GlobalParams.ScrollBarWidth)) && (pnt.Y <= base.Height)) || 
                GlobalParams.shiftKeyPressed)
            {
                int num3 = wheel * this.Xbar.SmallChange;
                int num4 = this.Xbar.Maximum - this.Xbar.Width;
                if ((((this.Xbar.Value - num3) <= num4) && ((this.Xbar.Value - num3) >= 0)) && (num4 >= 0))
                {
                    this.Xbar.Value -= num3;
                }
                else if (((this.Xbar.Value - num3) > num4) && (num4 >= 0))
                {
                    this.Xbar.Value = num4;
                }
                else if (((this.Xbar.Value - num3) < 0) || (num4 < 0))
                {
                    this.Xbar.Value = 0;
                }
            }
            else
            {
                int num5 = wheel * this.Ybar.SmallChange;
                int num6 = this.Ybar.Maximum - this.Ybar.Height;
                if ((((this.Ybar.Value - num5) <= num6) && ((this.Ybar.Value - num5) >= 0)) && (num6 >= 0))
                {
                    this.Ybar.Value -= num5;
                }
                else if (((this.Ybar.Value - num5) > num6) && (num6 >= 0))
                {
                    this.Ybar.Value = num6;
                }
                else if (((this.Ybar.Value - num5) < 0) || (num6 < 0))
                {
                    this.Ybar.Value = 0;
                }
            }
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            if ((this._bmp != null) && (this._graphics != null))
            {
                Rectangle clipRectangle = e.ClipRectangle;
                if ((clipRectangle.Left <= this.SheetSize.Width) && (clipRectangle.Top <= this.SheetSize.Height) || drawAll)
                {
                    if (clipRectangle.Right > this.SheetSize.Width)
                    {
                        e = new PaintEventArgs(e.Graphics, new Rectangle(clipRectangle.X, clipRectangle.Y, this.SheetSize.Width, clipRectangle.Height));
                    }
                    if (clipRectangle.Bottom > this.SheetSize.Height)
                    {
                        e = new PaintEventArgs(e.Graphics, new Rectangle(clipRectangle.X, clipRectangle.Y, clipRectangle.Width, this.SheetSize.Height));
                    }
                    if ((clipRectangle.Width != 0) && (clipRectangle.Height != 0))
                    {
                        this.selCtrls.Clear();
                        this._graphics.FillRectangle(this.whiteBrush, clipRectangle);
                        if (this.current != -1 && this.controls[this.current].Focused &&
                            this.selected_controls.Count == 0 &&
                            this.curElt.X <= clipRectangle.X + this.Xbar.Value &&
                            this.curElt.Y <= clipRectangle.Y + this.currentDelta + this.Ybar.Value &&
                            this.curElt.Right >= clipRectangle.Right + this.Xbar.Value &&
                            this.curElt.Bottom >= clipRectangle.Bottom + this.currentDelta + this.Ybar.Value &&
                            clipRectangle.Width <= this.controls[this.current].Size.Width &&
                            clipRectangle.Height <= this.controls[this.current].Size.Height &&
                            this.curElt.X == this.controls[this.current].Location.X + 2 &&
                            this.curElt.Y == this.controls[this.current].Location.Y + 2 &&
                            this.curElt.Width == this.controls[this.current].Size.Width - 4 &&
                            this.curElt.Height == this.controls[this.current].Size.Height - 4)
                        {
                            BaseControl control = this.controls[this.current];
                            this.ControlPaint(control, new PaintEventArgs(this._graphics, new Rectangle((control.Location.X - this.Xbar.Value) + 4, ((control.Location.Y - this.currentDelta) - this.Ybar.Value) + 4, control.Size.Width, control.Size.Height)));
                            this._graphics.DrawRectangle(new Pen(control.InDate ? Color.Black : Color.Gray), (int)((control.Location.X - this.Xbar.Value) + 2), (int)(((control.Location.Y - this.currentDelta) - this.Ybar.Value) + 2), (int)(control.Size.Width - 5), (int)(control.Size.Height - 5));
                            if (control.Border)
                            {
                                this._graphics.DrawRectangle(this.pen_black, (int)((control.Location.X - this.Xbar.Value) + 3), (int)(((control.Location.Y - this.currentDelta) - this.Ybar.Value) + 3), (int)(control.Size.Width - 7), (int)(control.Size.Height - 7));
                            }
                        }
                        else
                        {
                            if (this.drawGrid)
                            {
                                this.GridPainting(ref this._graphics, clipRectangle);
                            }
                            Size size = new Size();
                            int num3 = 0;
                            for (int i = 0; i < this.controls.Count; i++)
                            {
                                BaseControl control2 = this.controls[i];
                                size = control2.Size;
                                if ((clipRectangle.Left <= control2.Right - this.Xbar.Value - 2 &&
                                    clipRectangle.Right >= control2.Location.X - this.Xbar.Value + 2/* || flag*/) &&
                                    clipRectangle.Top <= control2.Bottom - num3 - this.Ybar.Value - 2 &&
                                    clipRectangle.Bottom >= control2.Location.Y - num3 - this.Ybar.Value + 2)
                                {
                                    /*if (flag)
                                    {
                                        this.StopHistory();
                                        control2.Location = new Point(this.Xbar.Value, control2.Location.Y);
                                        control2.Size = new Size(this.SheetSize.Width, control2.Size.Height);
                                        //this.ContinueHistory(UnReDoType.Control);
                                    }*/
                                    this.ControlPaint(control2, new PaintEventArgs(this._graphics,
                                        new Rectangle(control2.Location.X - this.Xbar.Value + 4,
                                        control2.Location.Y - this.Ybar.Value + 4, control2.Size.Width,
                                        control2.Size.Height)));
                                    if (control2.Border)
                                    {
                                        this._graphics.DrawRectangle(this.pen_black, (int)((control2.Location.X - this.Xbar.Value) + 3), (int)(((control2.Location.Y - num3) - this.Ybar.Value) + 3), (int)(control2.Size.Width - 7), (int)(control2.Size.Height - 7));
                                    }
                                    if (control2.Focused)
                                    {
                                        this._graphics.DrawRectangle(control2.InDate ? this.pen_black : this.pen_gray, (int)((control2.Location.X - this.Xbar.Value) + 2), (int)(((control2.Location.Y - num3) - this.Ybar.Value) + 2), (int)(control2.Size.Width - 5), (int)(control2.Size.Height - 5));
                                    }
                                    else if (control2.Selected)
                                    {
                                        this.selCtrls.Add(new Rectangle((control2.Location.X - this.Xbar.Value) + 3, ((control2.Location.Y - num3) - this.Ybar.Value) + 3, control2.Size.Width - 6, control2.Size.Height - 6));
                                        this.RectangleDrawing(this._graphics, new Rectangle((control2.Location.X - this.Xbar.Value) + 2, ((control2.Location.Y - num3) - this.Ybar.Value) + 2, control2.Size.Width - 5, control2.Size.Height - 5));
                                    }
                                    if (control2.Size != size)
                                    {
                                        this.CanvasResizer(this.controls[i]);
                                    }
                                }
                            }
                            for (int i = 0; i < connectors.Count; i++)
                            {
                                Point[] newPoints = connectors[i].Points.
                                    Select(p => new Point(p.X - Xbar.Value, p.Y - Ybar.Value)).ToArray();
                                this._graphics.DrawLines(this.pen_black, newPoints);
                                if (connectors[i].Selected)
                                {
                                    this._graphics.FillRectangles(new SolidBrush(Color.FromArgb(255, this.selColor)),
                                        newPoints.Select(point => new Rectangle(point.X - 2, point.Y - 2, 5, 5)).ToArray());
                                }
                            }
                            for (int i = 0; i < connHotSpots.Count; i++)
                            {
                                GraphicsPath gp = new GraphicsPath(connHotSpots[i].Area.PathPoints.
                                    Select(p => new PointF(p.X - Xbar.Value, p.Y - Ybar.Value)).ToArray(),
                                    connHotSpots[i].Area.PathTypes);
                                this._graphics.FillPath(new SolidBrush(Color.Cyan), gp);
                                this._graphics.DrawPath(this.pen_black, gp);
                            }
                            if (startHS != null)
                            {
                                List<Point> newConnector = new List<Point>();
                                newConnector.Add(((ConnectedElement)startHS).ConnectionPoint);
                                //Connector.conCount = 0;
                                newConnector.AddRange(Connector.Connect((
                                    (ConnectedElement)startHS).ConnectionPoint, mousePos, this, startHS.Control,
                                    null));
                                newConnector.Add(mousePos);
                                this._graphics.DrawLines(this.pen_dash, newConnector.
                                    Select(p => new Point(p.X - Xbar.Value, p.Y - Ybar.Value)).ToArray());
                            }
                            if (connEntered != null)
                            {
                                this._graphics.FillPath(new SolidBrush(Color.FromArgb(180, this.selColor)), 
                                    new GraphicsPath(connEntered.ConnectorArea.PathPoints.Select(p=>
                                        new PointF(p.X-Xbar.Value,p.Y-Ybar.Value)).ToArray(),
                                        connEntered.ConnectorArea.PathTypes));
                            }
                            if (this.current == -1 || this.selected_controls.Count > 0)
                            {
                                this._graphics.DrawLine(this.pen_redcross, (int)(this.MousePlace.X - this.Xbar.Value), (int)((this.MousePlace.Y - this.Ybar.Value) + ((this.gridSize - 1) / 2)), (int)((this.MousePlace.X - this.Xbar.Value) + (this.gridSize - 1)), (int)((this.MousePlace.Y - this.Ybar.Value) + ((this.gridSize - 1) / 2)));
                                this._graphics.DrawLine(this.pen_redcross, (int)((this.MousePlace.X - this.Xbar.Value) + ((this.gridSize - 1) / 2)), (int)(this.MousePlace.Y - this.Ybar.Value), (int)((this.MousePlace.X - this.Xbar.Value) + ((this.gridSize - 1) / 2)), (int)((this.MousePlace.Y - this.Ybar.Value) + (this.gridSize - 1)));
                                this.redcrossvisible = true;
                            }
                            else
                            {
                                this.redcrossvisible = false;
                            }
                            e.Graphics.FillRectangle(this.brush_control, this.SheetSize.Width, this.SheetSize.Height, GlobalParams.ScrollBarWidth, GlobalParams.ScrollBarWidth);
                        }
                        if (this.flag || this.selCtrls.Count != 0)// || this.linesToDraw.Count != 0)
                        {
                            using (Graphics graphics = Graphics.FromImage(this._bmp))
                            {
                                /*int num5 = 0;
                                int num6; = this.linesToDraw.Count;
                                while (num5 < num6)
                                {
                                    graphics.SetColor(this.linesToDraw[num5].color, 0xff);
                                    graphics.DrawLine(this.linesToDraw[num5].stroke, this.linesToDraw[num5].x1, this.linesToDraw[num5].y1, this.linesToDraw[num5].x2, this.linesToDraw[num5].y2);
                                    num5++;
                                }
                                graphics.SetColor(this.selColor, 60);*/
                                if (this.flag)
                                {
                                    graphics.FillRectangle(new SolidBrush(Color.FromArgb(60, this.selColor)),
                                        new Rectangle(this.rc.Left + 1, this.rc.Top + 1, this.rc.Width - 2, this.rc.Height - 2));
                                }
                                for (int i = 0; i < this.selCtrls.Count; i++)
                                {
                                    graphics.FillRectangle(new SolidBrush(Color.FromArgb(60, this.selColor)), this.selCtrls[i]);
                                }
                            }
                            if (this.flag)
                            {
                                this.RectangleDrawing(this._graphics, new Rectangle(this.rc.Left, this.rc.Top, (this.rc.Right - this.rc.Left) - 1, (this.rc.Bottom - this.rc.Top) - 1));
                            }
                        }
                        if (this.IsPickedUp)
                        {
                            for (int i = this.selected.Length - 1; i >= 0; i--)
                            {
                                this.RectangleDrawing(this._graphics, new Rectangle(this.selected[i].Left, this.selected[i].Top, (this.selected[i].Right - this.selected[i].Left) - 1, (this.selected[i].Bottom - this.selected[i].Top) - 1));
                            }
                        }
                        e.Graphics.DrawImage(this._bmp, clipRectangle, clipRectangle, GraphicsUnit.Pixel);
                        //base.OnPaint(e);
                    }
                }
            }
        }

        public void Draw(PaintEventArgs e) 
        {
            Bitmap _bmp = new Bitmap(e.ClipRectangle.Width, e.ClipRectangle.Height);
            Graphics _graphics = Graphics.FromImage(_bmp);
            if ((this._bmp != null) && (this._graphics != null))
            {
                Rectangle clipRectangle = e.ClipRectangle;
                if ((clipRectangle.Width != 0) && (clipRectangle.Height != 0))
                {
                    this.selCtrls.Clear();
                    this._graphics.FillRectangle(this.whiteBrush, clipRectangle);
                    if (this.current != -1 && this.controls[this.current].Focused &&
                        this.selected_controls.Count == 0 &&
                        this.curElt.X <= clipRectangle.X &&
                        this.curElt.Y <= clipRectangle.Y + this.currentDelta &&
                        this.curElt.Right >= clipRectangle.Right &&
                        this.curElt.Bottom >= clipRectangle.Bottom + this.currentDelta &&
                        clipRectangle.Width <= this.controls[this.current].Size.Width &&
                        clipRectangle.Height <= this.controls[this.current].Size.Height &&
                        this.curElt.X == this.controls[this.current].Location.X + 2 &&
                        this.curElt.Y == this.controls[this.current].Location.Y + 2 &&
                        this.curElt.Width == this.controls[this.current].Size.Width - 4 &&
                        this.curElt.Height == this.controls[this.current].Size.Height - 4)
                    {
                        BaseControl control = this.controls[this.current];
                        this.ControlPaint(control, new PaintEventArgs(this._graphics,
                            new Rectangle(control.Location.X + 4, control.Location.Y - this.currentDelta + 4,
                                control.Size.Width, control.Size.Height)));
                        this._graphics.DrawRectangle(new Pen(control.InDate ? Color.Black : Color.Gray), 
                            (int)((control.Location.X) + 2), (int)(control.Location.Y - this.currentDelta + 2),
                            (int)(control.Size.Width - 5), (int)(control.Size.Height - 5));
                        if (control.Border)
                        {
                            this._graphics.DrawRectangle(this.pen_black, (int)(control.Location.X + 3),
                                (int)(control.Location.Y - this.currentDelta + 3), (int)(control.Size.Width - 7),
                                (int)(control.Size.Height - 7));
                        }
                    }
                    else
                    {
                        if (this.drawGrid)
                        {
                            this.GridPainting(ref this._graphics, clipRectangle);
                        }
                        Size size = new Size();
                        int num3 = 0;
                        for (int i = 0; i < this.controls.Count; i++)
                        {
                            BaseControl control2 = this.controls[i];
                            size = control2.Size;
                            if ((clipRectangle.Left <= control2.Right - 2 &&
                                clipRectangle.Right >= control2.Location.X + 2/* || flag*/) &&
                                clipRectangle.Top <= control2.Bottom - num3 - 2 &&
                                clipRectangle.Bottom >= control2.Location.Y - num3 + 2)
                            {
                                /*if (flag)
                                {
                                    this.StopHistory();
                                    control2.Location = new Point(this.Xbar.Value, control2.Location.Y);
                                    control2.Size = new Size(this.SheetSize.Width, control2.Size.Height);
                                    //this.ContinueHistory(UnReDoType.Control);
                                }*/
                                this.ControlPaint(control2, new PaintEventArgs(this._graphics,
                                    new Rectangle(control2.Location.X + 4, control2.Location.Y + 4,
                                        control2.Size.Width, control2.Size.Height)));
                                if (control2.Border)
                                {
                                    this._graphics.DrawRectangle(this.pen_black, (int)(control2.Location.X + 3),
                                        (int)(control2.Location.Y - num3 + 3), (int)(control2.Size.Width - 7),
                                        (int)(control2.Size.Height - 7));
                                }
                                if (control2.Focused)
                                {
                                    this._graphics.DrawRectangle(control2.InDate ? this.pen_black : this.pen_gray,
                                        (int)(control2.Location.X + 2), (int)(control2.Location.Y - num3 + 2),
                                        (int)(control2.Size.Width - 5), (int)(control2.Size.Height - 5));
                                }
                                else if (control2.Selected)
                                {
                                    this.selCtrls.Add(new Rectangle(control2.Location.X + 3, 
                                        control2.Location.Y - num3 + 3, control2.Size.Width - 6,
                                        control2.Size.Height - 6));
                                    this.RectangleDrawing(this._graphics, new Rectangle(control2.Location.X + 2,
                                        control2.Location.Y - num3 + 2, control2.Size.Width - 5,
                                        control2.Size.Height - 5));
                                }
                                if (control2.Size != size)
                                {
                                    this.CanvasResizer(this.controls[i]);
                                }
                            }
                        }
                        for (int i = 0; i < connectors.Count; i++)
                        {
                            Point[] newPoints = connectors[i].Points;
                            this._graphics.DrawLines(this.pen_black, newPoints);
                            if (connectors[i].Selected)
                            {
                                this._graphics.FillRectangles(new SolidBrush(Color.FromArgb(255, this.selColor)),
                                    newPoints.Select(point => new Rectangle(point.X - 2, point.Y - 2, 5, 5)).ToArray());
                            }
                        }
                        for (int i = 0; i < connHotSpots.Count; i++)
                        {
                            GraphicsPath gp = connHotSpots[i].Area;
                            this._graphics.FillPath(new SolidBrush(Color.Cyan), gp);
                            this._graphics.DrawPath(this.pen_black, gp);
                        }
                        if (startHS != null)
                        {
                            List<Point> newConnector = new List<Point>();
                            newConnector.Add(((ConnectedElement)startHS).ConnectionPoint);
                            //Connector.conCount = 0;
                            newConnector.AddRange(Connector.Connect((
                                (ConnectedElement)startHS).ConnectionPoint, mousePos, this,startHS.Control,null));
                            newConnector.Add(mousePos);
                            this._graphics.DrawLines(this.pen_dash, newConnector.ToArray());
                        }
                        if (connEntered != null)
                        {
                            this._graphics.FillPath(new SolidBrush(Color.FromArgb(180, this.selColor)), connEntered.ConnectorArea);
                        }
                        if (this.current == -1 || this.selected_controls.Count > 0)
                        {
                            this._graphics.DrawLine(this.pen_redcross, (int)(this.MousePlace.X), (int)((this.MousePlace.Y) + ((this.gridSize - 1) / 2)), (int)(this.MousePlace.X + (this.gridSize - 1)), (int)(this.MousePlace.Y  + ((this.gridSize - 1) / 2)));
                            this._graphics.DrawLine(this.pen_redcross, (int)((this.MousePlace.X) + ((this.gridSize - 1) / 2)), (int)(this.MousePlace.Y), (int)(this.MousePlace.X + ((this.gridSize - 1) / 2)), (int)(this.MousePlace.Y + this.gridSize - 1));
                            this.redcrossvisible = true;
                        }
                        else
                        {
                            this.redcrossvisible = false;
                        }
                        //Not need to draw in Draw()
                        //e.Graphics.FillRectangle(this.brush_control, this.SheetSize.Width, this.SheetSize.Height, GlobalParams.ScrollBarWidth, GlobalParams.ScrollBarWidth);
                    }
                    if (this.flag || this.selCtrls.Count != 0)// || this.linesToDraw.Count != 0)
                    {
                        using (Graphics graphics = Graphics.FromImage(this._bmp))
                        {
                            /*int num5 = 0;
                            int num6; = this.linesToDraw.Count;
                            while (num5 < num6)
                            {
                                graphics.SetColor(this.linesToDraw[num5].color, 0xff);
                                graphics.DrawLine(this.linesToDraw[num5].stroke, this.linesToDraw[num5].x1, this.linesToDraw[num5].y1, this.linesToDraw[num5].x2, this.linesToDraw[num5].y2);
                                num5++;
                            }
                            graphics.SetColor(this.selColor, 60);*/
                            if (this.flag)
                            {
                                graphics.FillRectangle(new SolidBrush(Color.FromArgb(60, this.selColor)),
                                    new Rectangle(this.rc.Left + 1, this.rc.Top + 1, this.rc.Width - 2, this.rc.Height - 2));
                            }
                            for (int i = 0; i < this.selCtrls.Count; i++)
                            {
                                graphics.FillRectangle(new SolidBrush(Color.FromArgb(60, this.selColor)), this.selCtrls[i]);
                            }
                        }
                        if (this.flag)
                        {
                            this.RectangleDrawing(this._graphics, new Rectangle(this.rc.Left, this.rc.Top, (this.rc.Right - this.rc.Left) - 1, (this.rc.Bottom - this.rc.Top) - 1));
                        }
                    }
                    if (this.IsPickedUp)
                    {
                        for (int i = this.selected.Length - 1; i >= 0; i--)
                        {
                            this.RectangleDrawing(this._graphics, new Rectangle(this.selected[i].Left, this.selected[i].Top, (this.selected[i].Right - this.selected[i].Left) - 1, (this.selected[i].Bottom - this.selected[i].Top) - 1));
                        }
                    }
                    e.Graphics.DrawImage(this._bmp, clipRectangle, clipRectangle, GraphicsUnit.Pixel);
                    //base.OnPaint(e);
                }

            }
        }

        protected override void OnPaintBackground(PaintEventArgs e)
        {
        }

        protected override void OnResize(EventArgs e)
        {
            if ((this.SheetSize.Width >= 1) && (this.SheetSize.Height >= 1))
            {
                if (((this._bmp == null) || (this._bmp.Width != this.SheetSize.Width)) || (this._bmp.Height != this.SheetSize.Height))
                {
                    this._bmp = new Bitmap(this.SheetSize.Width, this.SheetSize.Height);
                    this._graphics = Graphics.FromImage(this._bmp);
                }
                this.Xbar.Size = new Size(this.Width - GlobalParams.ScrollBarWidth, GlobalParams.ScrollBarWidth);
                this.Xbar.Location = new Point(0, this.Height - GlobalParams.ScrollBarWidth);
                this.Xbar.LargeChange = this.Xbar.Width;
                this.Xbar.SmallChange = this.gridSize;
                this.Ybar.Size = new Size(17, this.Height - GlobalParams.ScrollBarWidth);
                this.Ybar.Location = new Point(this.Width - GlobalParams.ScrollBarWidth, 0);
                this.Ybar.LargeChange = this.Ybar.Height;
                this.Ybar.SmallChange = this.gridSize;
                this.xBarWidth = this.Xbar.Width;
                this.yBarHeight = this.Ybar.Height;
                this.CanvasResizer();
            }
        }

        private void openerXMCD(XmlTextReader Reader, ref int errorsCount, ref int yAdd)
        {
            /*int num = 0;
            while (Reader.Read())
            {
                Reader.MoveToContent();
                if ((Reader.NodeType == XmlNodeType.Element) && (((Reader.Name == "pointReleaseData") || (Reader.Name == "metadata")) || ((Reader.Name == "settings") || (Reader.Name == "binaryContent"))))
                {
                    Reader.Skip();
                    continue;
                }
                if ((Reader.NodeType == XmlNodeType.EndElement) && ((Reader.Name == "regions") || (Reader.Name == "area")))
                {
                    num--;
                    if (num < 0)
                    {
                        return;
                    }
                    break;
                }
                if ((Reader.NodeType == XmlNodeType.Element) && (Reader.Name == "region"))
                {
                    num++;
                    int argb = LangSelection.clr[2].ToArgb();
                    int width = (int) (1.28 * Convert.ToDouble(Reader.GetAttribute("width").Replace('.', LangSelection.sep)));
                    int height = (int) (1.28 * Convert.ToDouble(Reader.GetAttribute("height").Replace('.', LangSelection.sep)));
                    int x = this.Grider((int) (1.28 * Convert.ToDouble(Reader.GetAttribute("left").Replace('.', LangSelection.sep))));
                    int y = this.Grider((((int) (1.28 * Convert.ToDouble(Reader.GetAttribute("align-y").Replace('.', LangSelection.sep)))) - (height / 2)) + yAdd);
                    string attribute = Reader.GetAttribute("background-color");
                    if ((Convert.ToBoolean(Reader.GetAttribute("show-highlight")) && (attribute != null)) && ((attribute != "") && (attribute != "inherit")))
                    {
                        argb = this.String2Color(attribute);
                    }
                    bool flag = Convert.ToBoolean(Reader.GetAttribute("show-border"));
                    Color[] clr = LangSelection.clr;
                    LangSelection.clr = new Color[] { LangSelection.clr[0], LangSelection.clr[1], Color.FromArgb(argb), LangSelection.clr[3], LangSelection.clr[4] };
                    while (Reader.Read())
                    {
                        Reader.MoveToContent();
                        if ((Reader.NodeType == XmlNodeType.EndElement) && (Reader.Name == "region"))
                        {
                            num--;
                            if (num < 0)
                            {
                                return;
                            }
                            break;
                        }
                        if ((Reader.NodeType == XmlNodeType.Element) && ((Reader.Name == "rendering") || (Reader.Name == "resultFormat")))
                        {
                            Reader.Skip();
                            continue;
                        }
                        if (Reader.Name.ToLower() == "math")
                        {
                            if (Reader.NodeType != XmlNodeType.EndElement)
                            {
                                string str2 = Reader.GetAttribute("disable-calc");
                                if (string.IsNullOrEmpty(str2))
                                {
                                    str2 = "false";
                                }
                                Collection<EquImage> array = new Collection<EquImage>();
                                Stack<int> parentId = new Stack<int>();
                                try
                                {
                                    this.RecurseParse(array, Reader, parentId);
                                    EquImage[] imageArray = PrefixToPostfix(array.ToArray());
                                    for (int i = imageArray.Length - 1; i >= 0; i--)
                                    {
                                        if (imageArray[i].Type == EquType.Function)
                                        {
                                            if ((imageArray[i].Text == "log") && (imageArray[i].ChildCount == 1))
                                            {
                                                imageArray[i].Text = LangSelection.FunctionName[0x19];
                                            }
                                            if (LangSelection.Type_ISO != 1)
                                            {
                                                for (int j = 0; j < LangSelection.FunctionName.Length; j++)
                                                {
                                                    if (imageArray[i].Text == LangSelection.TypeWORLD[j])
                                                    {
                                                        imageArray[i].Text = LangSelection.FunctionName[j];
                                                    }
                                                }
                                            }
                                            if (imageArray[i].Text == "Γ")
                                            {
                                                imageArray[i].Text = Function.Gamma;
                                            }
                                            else if ((imageArray[i].Text == Function.Nthroot) || (imageArray[i].Text == Function.Diff))
                                            {
                                                int num9;
                                                OPZAlg[] algArray = OPZAlg.Localizer(imageArray, i, out num9);
                                                if (algArray.Length == 2)
                                                {
                                                    for (int k = algArray.Length - 1; k >= 0; k--)
                                                    {
                                                        for (int m = 0; m < algArray[k].arr.Length; m++)
                                                        {
                                                            imageArray[i - num9--] = algArray[k].arr[m];
                                                        }
                                                    }
                                                }
                                            }
                                            else if (imageArray[i].Text == Function.Mat)
                                            {
                                                int num12;
                                                OPZAlg[] algArray2 = OPZAlg.Localizer(imageArray, i, out num12);
                                                imageArray[i - 2] = algArray2[0].arr[0];
                                                imageArray[i - 1] = algArray2[1].arr[0];
                                                Convert.ToInt32(algArray2[0].arr[0].Text);
                                                int num13 = Convert.ToInt32(algArray2[1].arr[0].Text);
                                                int index = 2;
                                                int num15 = 1;
                                                while (index < algArray2.Length)
                                                {
                                                    for (int n = 0; n < algArray2[index].arr.Length; n++)
                                                    {
                                                        imageArray[i - num12--] = algArray2[index].arr[n];
                                                    }
                                                    index += num13;
                                                    if (index >= algArray2.Length)
                                                    {
                                                        index = 2 + num15++;
                                                    }
                                                    if (num15 > num13)
                                                    {
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    MathControl control = new MathControl();
                                    control.Evaluate = !Convert.ToBoolean(str2);
                                    control.fraction_type = LangSelection.fraction_ISO;
                                    control.Size = new Size(width, height);
                                    control.Border = flag;
                                    this.ElementCreater(control, new Point(x, y), true, false, false, false);
                                    control.IMG = imageArray;
                                    control.RePainter();
                                }
                                catch
                                {
                                    errorsCount++;
                                    Reader.Skip();
                                }
                            }
                            continue;
                        }
                        if (Reader.Name.ToLower() == "text")
                        {
                            if (Reader.NodeType == XmlNodeType.EndElement)
                            {
                                continue;
                            }
                            string str3 = "";
                            while (Reader.Read())
                            {
                                Reader.MoveToContent();
                                if ((Reader.NodeType == XmlNodeType.EndElement) && (Reader.Name == "text"))
                                {
                                    break;
                                }
                                if (((Reader.NodeType == XmlNodeType.Element) && (Reader.Name.ToLower() == "p")) && (str3 != ""))
                                {
                                    str3 = str3 + "\r";
                                }
                                if (!string.IsNullOrEmpty(Reader.Value))
                                {
                                    str3 = str3 + Reader.Value;
                                }
                            }
                            TextControl control2 = new TextControl();
                            control2.Size = new Size(width, height);
                            control2.Border = flag;
                            this.ElementCreater(control2, new Point(x, y), true, false, false, false);
                            control2.Text = str3;
                            control2.RePainter();
                            continue;
                        }
                        if (Reader.Name.ToLower() == "area")
                        {
                            if (Reader.NodeType != XmlNodeType.EndElement)
                            {
                                string str4 = Reader.GetAttribute("is-collapsed");
                                string str5 = Reader.GetAttribute("show-icon");
                                AreaControl control3 = new AreaControl();
                                y += (height / 2) - 0x11;
                                if (string.IsNullOrEmpty(str4))
                                {
                                    control3.collapsed = false;
                                }
                                else
                                {
                                    control3.collapsed = Convert.ToBoolean(str4);
                                    if (control3.collapsed)
                                    {
                                        y += this.gridSize / 2;
                                    }
                                }
                                if (string.IsNullOrEmpty(str5))
                                {
                                    control3.top = false;
                                }
                                else
                                {
                                    control3.top = Convert.ToBoolean(str5);
                                }
                                control3.Size = new Size(this.CanvasSize.Width, 0x11);
                                control3.Border = flag;
                                this.ElementCreater(control3, new Point(x, this.Grider(y)), true, false, false, false);
                                control3.collapsedChanged += new CollapseStatusChanged(this.v1_collapsedChanged);
                                control3.RePainter();
                                if (control3.top)
                                {
                                    int num17 = control3.collapsed ? y : 0;
                                    this.openerXMCD(Reader, ref errorsCount, ref num17);
                                    AreaControl control4 = new AreaControl();
                                    control4.collapsed = false;
                                    control4.top = false;
                                    control4.Size = new Size(this.CanvasSize.Width, 0x11);
                                    control4.Border = flag;
                                    this.ElementCreater(control4, new Point(x, this.Grider(y + height)), true, false, false, false);
                                    control4.RePainter();
                                    yAdd += control3.collapsed ? height : 0;
                                }
                            }
                        }
                        else
                        {
                            errorsCount++;
                            Reader.Skip();
                        }
                    }
                    LangSelection.clr = clr;
                }
            }*/
        }

        private bool OpenXMCD(Stream stream)
        {
            this.StopHistory();
            int errorsCount = 0;
            XmlTextReader reader = null;
            try
            {
                reader = new XmlTextReader(stream);
                reader.Read();
                int yAdd = 0;
                this.openerXMCD(reader, ref errorsCount, ref yAdd);
            }
            catch (Exception exception)
            {
                //MessageBox.Show(exception.Message, LangSelection.FTitle);
                return false;
            }
            finally
            {
                reader.Close();
                this.CanvasResizer();
                this.controls.Sort();
                this.ReCalc();
                //this.ContinueHistory(UnReDoType.ControlAdd);
            }
            if (errorsCount > 0)
            {
                //MessageBox.Show(string.Format(SSException.GetErrorText(Error.XMCDFileCanNotBeFullyParsed), errorsCount.ToString()), LangSelection.FTitle);
            }
            return true;
        }

        public bool OpenXMCD(string fileName)
        {
            bool flag;
            try
            {
                using (FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                {
                    flag = this.OpenXMCD(stream);
                }
            }
            catch (Exception exception)
            {
                //MessageBox.Show(exception.Message, LangSelection.FTitle);
                flag = false;
            }
            return flag;
        }

        public bool OpenXML(Stream stream, bool outside)
        {
            if (outside)
            {
                this.StopHistory();
            }
            else
            {
                this.StartCacheHistory();
            }
            /*XmlTextReader reader = null;
            try
            {
                string str13;
                int num = LangSelection.fontsize_ISO;
                int count = -1;
                int num3 = -1;
                int num4 = LangSelection.Type_ISO;
                string str = "";
                Color[] clr = LangSelection.clr;
                this.Ybar.Refresh();
                this.Xbar.Refresh();
                reader = new XmlTextReader(stream);
                reader.Read();
                goto Label_13E4;
            Label_005B:
                if (reader.Value.IndexOf("version") != -1)
                {
                    string[] strArray = reader.Value.Split(new char[] { '"' });
                    string[] strArray2 = strArray[strArray.Length - 2].Split(new char[] { '.', ',' });
                    if ((Convert.ToInt16(strArray2[0]) <= 0) && (Convert.ToInt16(strArray2[1]) <= 50))
                    {
                        reader.Close();
                        return false;
                    }
                    goto Label_00EF;
                }
                reader.Read();
            Label_00E3:
                if (reader.NodeType == XmlNodeType.ProcessingInstruction)
                {
                    goto Label_005B;
                }
            Label_00EF:
                reader.MoveToContent();
                if ((reader.NodeType != XmlNodeType.Element) || !(reader.Name.ToLower() == "settings"))
                {
                    goto Label_048F;
                }
            Label_047F:
                while (reader.Read())
                {
                    reader.MoveToContent();
                    if (reader.NodeType == XmlNodeType.Element)
                    {
                        str = reader.Name.ToLower();
                    }
                    else
                    {
                        if ((reader.NodeType == XmlNodeType.EndElement) && (reader.Name.ToLower() == "settings"))
                        {
                            break;
                        }
                        if (reader.NodeType == XmlNodeType.Text)
                        {
                            switch (str)
                            {
                                case "editable":
                                    this.pageState = Convert.ToBoolean(reader.Value) ? CanvasEditStatus.Editable : CanvasEditStatus.ReadOnly;
                                    goto Label_01CD;

                                case "home":
                                    this.homeFile = reader.Value;
                                    break;

                                case "back":
                                    this.backFile = reader.Value;
                                    break;
                            }
                        }
                    }
                Label_01CD:
                    if ((str == "metadata") && (reader.NodeType == XmlNodeType.Element))
                    {
                        string attribute = reader.GetAttribute("lang");
                        CanvasInfo info = new CanvasInfo();
                        while (reader.Read())
                        {
                            reader.MoveToContent();
                            if (reader.NodeType == XmlNodeType.Element)
                            {
                                str = reader.Name.ToLower();
                            }
                            else
                            {
                                if ((reader.NodeType == XmlNodeType.EndElement) && (reader.Name.ToLower() == "metadata"))
                                {
                                    break;
                                }
                                if (reader.NodeType == XmlNodeType.Text)
                                {
                                    switch (str)
                                    {
                                        case "title":
                                        {
                                            info.Title = reader.Value;
                                            continue;
                                        }
                                        case "author":
                                        {
                                            info.Author = reader.Value;
                                            continue;
                                        }
                                        case "description":
                                        {
                                            info.Description = reader.Value;
                                            continue;
                                        }
                                        case "company":
                                        {
                                            info.Company = reader.Value;
                                            continue;
                                        }
                                        case "keywords":
                                            info.Keywords = reader.Value;
                                            break;
                                    }
                                }
                            }
                        }
                        if (string.IsNullOrEmpty(attribute))
                        {
                            attribute = "eng";
                        }
                        this.canvasInfo.Add(attribute.ToUpper(), info);
                        continue;
                    }
                    if ((str == "calculation") && (reader.NodeType == XmlNodeType.Element))
                    {
                        while (reader.Read())
                        {
                            reader.MoveToContent();
                            if (reader.NodeType == XmlNodeType.Element)
                            {
                                str = reader.Name.ToLower();
                            }
                            else
                            {
                                if ((reader.NodeType == XmlNodeType.EndElement) && (reader.Name.ToLower() == "calculation"))
                                {
                                    goto Label_047F;
                                }
                                if (reader.NodeType == XmlNodeType.Text)
                                {
                                    switch (str)
                                    {
                                        case "functions":
                                        {
                                            num4 = Convert.ToInt32(reader.Value);
                                            continue;
                                        }
                                        case "precision":
                                        {
                                            LangSelection.num_ISO = Convert.ToInt32(reader.Value);
                                            continue;
                                        }
                                    }
                                    if (!(str == "angle"))
                                    {
                                        goto Label_0419;
                                    }
                                    str13 = reader.Value;
                                    if (str13 != null)
                                    {
                                        if (!(str13 == "degrees"))
                                        {
                                            if (str13 == "radians")
                                            {
                                                goto Label_0411;
                                            }
                                        }
                                        else
                                        {
                                            LangSelection.corner_ISO = CornerType.Deg;
                                        }
                                    }
                                }
                            }
                            continue;
                        Label_0411:
                            LangSelection.corner_ISO = CornerType.Rad;
                            continue;
                        Label_0419:
                            if ((str == "fractions") && ((str13 = reader.Value) != null))
                            {
                                if (!(str13 == "auto"))
                                {
                                    if (str13 == "fraction")
                                    {
                                        goto Label_0466;
                                    }
                                    if (str13 == "decimal")
                                    {
                                        goto Label_046E;
                                    }
                                }
                                else
                                {
                                    LangSelection.fraction_ISO = FractionType.Auto;
                                }
                            }
                            continue;
                        Label_0466:
                            LangSelection.fraction_ISO = FractionType.Fraction;
                            continue;
                        Label_046E:
                            LangSelection.fraction_ISO = FractionType.None;
                        }
                    }
                }
                goto Label_13E4;
            Label_048F:
                if ((reader.NodeType == XmlNodeType.Element) && (reader.Name.ToLower() == "region"))
                {
                    count = this.controls.Count;
                    int num7 = 10;
                    int argb = 0;
                    int num9 = 0;
                    int width = 0;
                    int height = 0;
                    int num12 = 0;
                    int num13 = 0;
                    int num14 = 0;
                    int num15 = 0;
                    int num16 = 0;
                    int num17 = 0;
                    double num18 = 1.0;
                    double num19 = 1.0;
                    double num20 = 1.0;
                    bool flag = false;
                    int num5 = Convert.ToInt32(reader.GetAttribute("left")) * this.ctrlSize;
                    int num6 = Convert.ToInt32(reader.GetAttribute("top")) * this.ctrlSize;
                    if (reader.AttributeCount >= 7)
                    {
                        num7 = Convert.ToInt16(reader.GetAttribute("font-size"));
                        if (num7 == 0)
                        {
                            num7 = 10;
                        }
                        argb = this.String2Color(reader.GetAttribute("color"));
                        num9 = this.String2Color(reader.GetAttribute("background-color"));
                    }
                    width = Convert.ToInt32(reader.GetAttribute("width")) * this.ctrlSize;
                    height = Convert.ToInt32(reader.GetAttribute("height")) * this.ctrlSize;
                    string str4 = reader.GetAttribute("border");
                    if (!string.IsNullOrEmpty(str4))
                    {
                        flag = Convert.ToBoolean(str4);
                    }
                    Point point = outside ? new Point(0, 0) : this.MousePlace;
                    while (reader.Read())
                    {
                        Stack stack;
                        reader.MoveToContent();
                        if ((reader.NodeType == XmlNodeType.EndElement) && (reader.Name == "region"))
                        {
                            if (((num3 == count) && (num3 != -1)) && ((this.controls.Count > num3) && (this.controls[num3] is TextControl)))
                            {
                                ((TextControl) this.controls[num3]).SetCurrentText();
                            }
                            break;
                        }
                        if ((reader.NodeType != XmlNodeType.Element) || (!(reader.Name.ToLower() == "math") && !(reader.Name.ToLower() == "plot")))
                        {
                            goto Label_0DEC;
                        }
                        bool flag2 = true;
                        if (reader.Name == "plot")
                        {
                            flag2 = false;
                        }
                        string str5 = reader.GetAttribute("evaluate");
                        if (string.IsNullOrEmpty(str5))
                        {
                            str5 = "true";
                        }
                        string str6 = reader.GetAttribute("error");
                        if (string.IsNullOrEmpty(str6))
                        {
                            str6 = "-1";
                        }
                        PlotType type = PlotType.Plot2D;
                        RenderType points = RenderType.Points;
                        FractionType undefined = FractionType.Undefined;
                        if (flag2)
                        {
                            goto Label_0903;
                        }
                        str13 = reader.GetAttribute("type");
                        if (str13 != null)
                        {
                            if (!(str13 == "2d"))
                            {
                                if (str13 == "3d")
                                {
                                    goto Label_0731;
                                }
                            }
                            else
                            {
                                type = PlotType.Plot2D;
                            }
                        }
                        goto Label_0734;
                    Label_0731:
                        type = PlotType.Plot3D;
                    Label_0734:
                        if ((str13 = reader.GetAttribute("render")) != null)
                        {
                            if (!(str13 == "points"))
                            {
                                if (str13 == "lines")
                                {
                                    goto Label_0767;
                                }
                            }
                            else
                            {
                                points = RenderType.Points;
                            }
                        }
                        goto Label_076A;
                    Label_0767:
                        points = RenderType.Lines;
                    Label_076A:
                        num18 = Convert.ToDouble(reader.GetAttribute("scale_x").Replace(',', LangSelection.sep).Replace('.', LangSelection.sep));
                        if (num18 == 0.0)
                        {
                            num18 = 1.0;
                        }
                        else
                        {
                            num19 = Convert.ToDouble(reader.GetAttribute("scale_y").Replace(',', LangSelection.sep).Replace('.', LangSelection.sep));
                            num20 = Convert.ToDouble(reader.GetAttribute("scale_z").Replace(',', LangSelection.sep).Replace('.', LangSelection.sep));
                            num12 = Convert.ToInt32(reader.GetAttribute("rotate_x").Replace(',', LangSelection.sep).Replace('.', LangSelection.sep));
                            num13 = Convert.ToInt32(reader.GetAttribute("rotate_y").Replace(',', LangSelection.sep).Replace('.', LangSelection.sep));
                            num14 = Convert.ToInt32(reader.GetAttribute("rotate_z").Replace(',', LangSelection.sep).Replace('.', LangSelection.sep));
                            num15 = Convert.ToInt32(reader.GetAttribute("transpose_x").Replace(',', LangSelection.sep).Replace('.', LangSelection.sep));
                            num16 = Convert.ToInt32(reader.GetAttribute("transpose_y").Replace(',', LangSelection.sep).Replace('.', LangSelection.sep));
                            num17 = Convert.ToInt32(reader.GetAttribute("transpose_z").Replace(',', LangSelection.sep).Replace('.', LangSelection.sep));
                        }
                        goto Label_0955;
                    Label_0903:
                        if ((reader.AttributeCount == 1) && ((str13 = reader.GetAttribute("fraction-type")) != null))
                        {
                            if (!(str13 == "auto"))
                            {
                                if (str13 == "fraction")
                                {
                                    goto Label_094D;
                                }
                                if (str13 == "none")
                                {
                                    goto Label_0952;
                                }
                            }
                            else
                            {
                                undefined = FractionType.Auto;
                            }
                        }
                        goto Label_0955;
                    Label_094D:
                        undefined = FractionType.Fraction;
                        goto Label_0955;
                    Label_0952:
                        undefined = FractionType.None;
                    Label_0955:
                        stack = new Stack();
                        string str7 = "";
                        int childCount = 0;
                        while (reader.Read())
                        {
                            string str8;
                            reader.MoveToContent();
                            if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "e"))
                            {
                                str7 = reader.GetAttribute("type");
                                if (reader.AttributeCount > 1)
                                {
                                    childCount = Convert.ToInt16(reader.GetAttribute("args"));
                                }
                            }
                            else if ((reader.NodeType == XmlNodeType.EndElement) && ((reader.Name.ToLower() == "math") || (reader.Name.ToLower() == "plot")))
                            {
                                break;
                            }
                            if ((reader.NodeType == XmlNodeType.Text) && ((str13 = str7) != null))
                            {
                                if (!(str13 == "operand"))
                                {
                                    if (str13 == "operator")
                                    {
                                        goto Label_0A7C;
                                    }
                                    if (str13 == "function")
                                    {
                                        goto Label_0A96;
                                    }
                                    if (str13 == "bracket")
                                    {
                                        goto Label_0B08;
                                    }
                                }
                                else
                                {
                                    stack.Push(new EquImage(reader.Value.Replace(',', LangSelection.sep).Replace('.', LangSelection.sep), EquType.Operand, 0));
                                }
                            }
                            continue;
                        Label_0A7C:
                            stack.Push(new EquImage(reader.Value, EquType.Operator, childCount));
                            continue;
                        Label_0A96:
                            str8 = reader.Value;
                            if (num4 != LangSelection.Type_ISO)
                            {
                                string[] strArray3 = (num4 == 0) ? LangSelection.TypeEURO : LangSelection.TypeWORLD;
                                string[] strArray4 = (num4 == 0) ? LangSelection.TypeWORLD : LangSelection.TypeEURO;
                                for (int j = 0; j < strArray3.Length; j++)
                                {
                                    if (str8 == strArray3[j])
                                    {
                                        str8 = strArray4[j];
                                        break;
                                    }
                                }
                            }
                            stack.Push(new EquImage(str8, EquType.Function, childCount));
                            continue;
                        Label_0B08:
                            stack.Push(new EquImage("(", EquType.Bracket, 1));
                        }
                        EquImage[] imageArray = new EquImage[stack.Count];
                        for (int i = imageArray.Length - 1; i >= 0; i--)
                        {
                            imageArray[i] = (EquImage) stack.Pop();
                        }
                        LangSelection.fontsize_ISO = num7;
                        Color[] colorArray2 = new Color[] { Color.FromArgb(argb), LangSelection.clr[1], Color.FromArgb(num9), LangSelection.clr[3], LangSelection.clr[4] };
                        LangSelection.clr = colorArray2;
                        if (flag2)
                        {
                            MathControl control = new MathControl();
                            control.Evaluate = Convert.ToBoolean(str5);
                            if (str6 != "-1")
                            {
                                control.errorId = (Error) Convert.ToInt32(str6);
                                control.ErrorText = SSException.GetErrorText(control.errorId);
                            }
                            control.fraction_type = undefined;
                            control.Size = new Size(width, height);
                            control.Border = flag;
                            num3 = this.ElementCreater(control, new Point(num5 + point.X, num6 + point.Y), true, false, false, !outside);
                            control.IMG = imageArray;
                            control.Selected = !outside;
                            control.RePainter();
                        }
                        else
                        {
                            PlotControl control2 = new PlotControl();
                            control2.Evaluate = Convert.ToBoolean(str5);
                            if (str6 != "-1")
                            {
                                control2.errorId = (Error) Convert.ToInt32(str6);
                                control2.ErrorText = SSException.GetErrorText(control2.errorId);
                            }
                            control2.Size = new Size(width, height);
                            control2.Border = flag;
                            num3 = this.ElementCreater(control2, new Point(num5 + point.X, num6 + point.Y), true, false, false, !outside);
                            control2.math.IMG = imageArray;
                            control2.RType = points;
                            control2.PType = type;
                            control2.math.Focused = false;
                            control2.scale_x = num18;
                            control2.scale_y = num19;
                            control2.scale_z = num20;
                            control2.rotate_x = num12;
                            control2.rotate_y = num13;
                            control2.rotate_z = num14;
                            control2.transpose_x = num15;
                            control2.transpose_y = num16;
                            control2.transpose_z = num17;
                            control2.prefs = true;
                            control2.Selected = !outside;
                            control2.Reset();
                            control2.ren.Refresh();
                            control2.ren.Actualize();
                            control2.ren.RePainter();
                        }
                        continue;
                    Label_0DEC:
                        if ((reader.NodeType == XmlNodeType.Element) && (reader.Name.ToLower() == "text"))
                        {
                            TextControl control3;
                            string str9 = reader.GetAttribute("lang");
                            if (string.IsNullOrEmpty(str9))
                            {
                                str9 = LangSelection.CurLang3Letter;
                            }
                            str9 = str9.ToUpper();
                            string text = "";
                            string str11 = "";
                            bool flag3 = false;
                            bool flag4 = false;
                            while (reader.Read())
                            {
                                reader.MoveToContent();
                                if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "p"))
                                {
                                    flag3 = Convert.ToBoolean(reader.GetAttribute("bold"));
                                    str11 = reader.GetAttribute("href");
                                    if (reader.AttributeCount == 3)
                                    {
                                        flag4 = Convert.ToBoolean(reader.GetAttribute("build-in"));
                                    }
                                }
                                else if ((reader.NodeType == XmlNodeType.EndElement) && (reader.Name == "text"))
                                {
                                    break;
                                }
                                if (reader.NodeType == XmlNodeType.Text)
                                {
                                    if (flag4)
                                    {
                                        text = LangSelection.MathBook[Convert.ToInt32(reader.Value)];
                                    }
                                    else
                                    {
                                        text = reader.Value;
                                    }
                                }
                            }
                            LangSelection.fontsize_ISO = num7;
                            colorArray2 = new Color[] { Color.FromArgb(argb), LangSelection.clr[1], Color.FromArgb(num9), LangSelection.clr[3], LangSelection.clr[4] };
                            LangSelection.clr = colorArray2;
                            if (num3 != count)
                            {
                                control3 = new TextControl();
                                control3.Size = new Size(width, height);
                                control3.Border = flag;
                                num3 = this.ElementCreater(control3, new Point(num5 + point.X, num6 + point.Y), true, false, false, !outside);
                            }
                            else
                            {
                                control3 = (TextControl) this.controls[num3];
                            }
                            control3.SetText(text, str9);
                            control3.link = str11;
                            control3.bold = flag3;
                            control3.Selected = !outside;
                            control3.RePainter();
                            continue;
                        }
                        if ((reader.NodeType == XmlNodeType.Element) && (reader.Name.ToLower() == "area"))
                        {
                            Convert.ToBoolean(reader.GetAttribute("single"));
                            bool flag5 = Convert.ToBoolean(reader.GetAttribute("is-collapsed"));
                            reader.GetAttribute("name");
                            Convert.ToBoolean(reader.GetAttribute("show-name"));
                            LangSelection.fontsize_ISO = num7;
                            colorArray2 = new Color[] { Color.FromArgb(argb), LangSelection.clr[1], Color.FromArgb(num9), LangSelection.clr[3], LangSelection.clr[4] };
                            LangSelection.clr = colorArray2;
                            AreaControl control4 = new AreaControl();
                            control4.collapsed = flag5;
                            control4.Size = new Size(this.CanvasSize.Width, 0x11);
                            control4.Border = flag;
                            num3 = this.ElementCreater(control4, new Point(0, num6 + point.Y), true, false, false, !outside);
                            control4.Selected = !outside;
                            control4.RePainter();
                            continue;
                        }
                        if ((reader.NodeType == XmlNodeType.Element) && (reader.Name.ToLower() == "picture"))
                        {
                            MemoryStream imageFileStream = new MemoryStream();
                            while (reader.Read())
                            {
                                reader.MoveToContent();
                                if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "raw"))
                                {
                                    string str12 = reader.GetAttribute("format");
                                    Stack stack2 = new Stack();
                                    int num24 = 0;
                                    byte[] array = new byte[50];
                                    do
                                    {
                                        num24 = reader.ReadBinHex(array, 0, 50);
                                        for (int m = 0; m < num24; m++)
                                        {
                                            stack2.Push(array[m]);
                                        }
                                    }
                                    while (reader.Name == "raw");
                                    object[] objArray = stack2.ToArray();
                                    byte[] buffer = new byte[objArray.Length];
                                    for (int k = 0; k < objArray.Length; k++)
                                    {
                                        buffer[(objArray.Length - k) - 1] = (byte) objArray[k];
                                    }
                                    switch (str12)
                                    {
                                        case "bmp":
                                        case "png":
                                            imageFileStream = new MemoryStream(buffer.Length);
                                            imageFileStream.Write(buffer, 0, buffer.Length);
                                            break;
                                    }
                                }
                                else if ((reader.NodeType == XmlNodeType.EndElement) && (reader.Name == "picture"))
                                {
                                    break;
                                }
                            }
                            LangSelection.fontsize_ISO = num7;
                            colorArray2 = new Color[] { Color.FromArgb(argb), LangSelection.clr[1], Color.FromArgb(num9), LangSelection.clr[3], LangSelection.clr[4] };
                            LangSelection.clr = colorArray2;
                            PictureControl control5 = new PictureControl();
                            control5.Border = flag;
                            num3 = this.ElementCreater(control5, new Point(num5 + point.X, num6 + point.Y), true, false, false, !outside);
                            control5.LoadImageFromStream(imageFileStream);
                            imageFileStream.Close();
                            control5.Selected = !outside;
                            control5.RePainter();
                        }
                    }
                }
            Label_13E4:
                if (reader.Read())
                {
                    goto Label_00E3;
                }
                LangSelection.fontsize_ISO = num;
                LangSelection.clr = clr;
                this.CanvasResizer();
                this.controls.Sort();
                if (outside)
                {
                    this.MousePlace = new Point(0, 0);
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message, LangSelection.FTitle);
                return false;
            }
            finally
            {
                reader.Close();
                this.ReCalc();
                this.ContinueHistory(UnReDoType.ControlAdd);
            }*/
            return true;
        }

        public bool OpenXML(string fileName, bool outside)
        {
            if ((fileName == "") || !File.Exists(fileName))
            {
                if (outside)
                {
                    //MessageBox.Show(SSException.GetErrorText(Error.CanNotFindFile) + fileName, LangSelection.FTitle);
                }
                return false;
            }
            this.selfFile = fileName;
            try
            {
                using (FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                {
                    this.OpenXML(stream, outside);
                }
            }
            catch (Exception exception)
            {
                //MessageBox.Show(exception.Message, LangSelection.FTitle);
                return false;
            }
            this.localpath = "";
            string[] strArray = fileName.Split(new char[] { Path.DirectorySeparatorChar });
            for (int i = 0; i < (strArray.Length - 1); i++)
            {
                this.localpath = this.localpath + strArray[i] + Path.DirectorySeparatorChar;
            }
            return true;
        }

        public void PageStatusManager()
        {
            /*if (this.onPageStatusChanged != null)
            {
                SheetStatus pageStatus = this.GetPageStatus();
                if ((((this.fullPageStatus == null) || (pageStatus.inCtrlSelection != this.fullPageStatus.inCtrlSelection)) || ((pageStatus.pageSelection != this.fullPageStatus.pageSelection) || (pageStatus.pageStatus != this.fullPageStatus.pageStatus))) || (((pageStatus.clipboardStatus != this.fullPageStatus.clipboardStatus) || (pageStatus.unReDoStatus != this.fullPageStatus.unReDoStatus)) || (pageStatus.controlType != this.fullPageStatus.controlType)))
                {
                    this.fullPageStatus = pageStatus;
                    this.onPageStatusChanged(this, pageStatus);
                }
            }*/
        }

        public void ParseInsertString(string value)
        {
            #region value == "INSERTTEXT"
            if (value == "INSERTTEXT")
            {
                if (this.current == -1 || this.selected_controls.Count > 0)
                {
                    TextControl control = new TextControl();
                    control.Text = "";
                    this.ElementCreater(control, new Point(this.MousePlace.X, this.MousePlace.Y), true, true, true, true);
                    control.PrePainter();
                    control.RePainter();
                    this.CanvasResizer(control);
                    this.ScrollControlToScreenBoundsSmooth(control);
                }
                return;
            }
            #endregion
            #region value.StartsWith("INSERTBLOCK")
            if (value.StartsWith("INSERTBLOCK"))
            {
                if (this.current == -1 || this.selected_controls.Count > 0)
                {
                    int index = 0;
                    string[] parts = value.Split('|');
                    for (int i = 0; i < this.controls.Count; i++)
                    {
                        BlockControl bc = this.controls[i] as BlockControl;
                        if (bc != null && bc.Type == parts[1] && index < bc.Index) index = bc.Index;
                    }
                    BlockControl control = new BlockControl(parts[1], ++index);
                    this.ElementCreater(control, new Point(this.MousePlace.X, this.MousePlace.Y), true, true, true, true);
                    control.PrePainter();
                    control.RePainter();
                    this.CanvasResizer(control);
                    this.ScrollControlToScreenBoundsSmooth(control);
                }
                return;
            }
            #endregion
            #region value == "INSERTPICTURE"
            if (value == "INSERTPICTURE")
            {
                if ((this.current == -1) || (this.selected_controls.Count > 0))
                {
                    PictureControl control = new PictureControl();
                    this.ElementCreater(control, new Point(this.MousePlace.X, this.MousePlace.Y), true, true, true, true);
                    control.PrePainter();
                    control.RePainter();
                    this.CanvasResizer(control);
                    this.ScrollControlToScreenBoundsSmooth(control);
                }
                return;
            }
            #endregion
            #region value.StartsWith("INSERTPICB|")
            if (value.StartsWith("INSERTPICB|"))
            {
                try
                {
                    string imageFileName = value.Remove(0, 11);
                    PictureControl control7 = new PictureControl();
                    this.ElementCreater(control7, new Point(this.MousePlace.X, this.MousePlace.Y), true, true, true, true);
                    control7.LoadImage(imageFileName);
                    control7.PrePainter();
                    control7.RePainter();
                    this.CanvasResizer(control7);
                    this.ScrollControlToScreenBoundsSmooth(control7);
                }
                catch (Exception exception)
                {
                    MessageBox.Show(exception.Message);
                }
                return;
            }
            #endregion
            if (this.current == -1)
            {
                #region value == "PAGEUP"
                if (value == "PAGEUP")
                {
                    if (this.Ybar.Value - this.Ybar.LargeChange >= 0)
                    {
                        this.Ybar.Value -= this.Grider(this.Ybar.LargeChange);
                        return;
                    }
                    this.Ybar.Value = 0;
                    return;
                }
                #endregion
                #region value == "PAGEDOWN"
                if (value == "PAGEDOWN")
                {
                    if (this.Ybar.Value + this.Ybar.LargeChange <= this.Ybar.Maximum - this.Ybar.LargeChange)
                    {
                        this.Ybar.Value += this.Grider(this.Ybar.LargeChange);
                        return;
                    }
                    this.Ybar.Value = this.Grider(this.Ybar.Maximum - this.Ybar.LargeChange);
                    return;
                }
                #endregion
                #region value == "HOME"
                if (value == "HOME")
                {
                    this.Ybar.Value = 0;
                    return;
                }
                #endregion
                #region value == "END"
                if (value == "END")
                {
                    this.Ybar.Value = this.Ybar.Maximum - this.Ybar.LargeChange;
                    return;
                }
                #endregion

                if (this.selected_controls.Count > 0 || this.connectors.Where(c=>c.Selected).Count()>0)
                {
                    #region "COPY" "CUT" "\b" "BACK" "DELETE"
                    if ((value == "COPY") || (value == "CUT"))
                    {
                        this.ClipboardSetData();
                    }
                    if (((value == "\b") || (value == "BACK")) || ((value == "DELETE") || (value == "CUT")))
                    {
                        if (this.selected_controls.Count > 0)
                        {
                            this.RemoveControls(this.selected_controls.ToArray());
                        }
                        int[] selected_connectors = this.connectors.Where(c => c.Selected).Select(c =>
                            this.connectors.IndexOf(c)).ToArray();
                        if (selected_connectors.Length > 0)
                        {
                            this.RemoveConnectors(selected_connectors);
                        }
                    }
                    if (this.current != -1)
                    {
                        this.DoINeedToDeleteElement(this.current);
                    }
                    #endregion
                    #region value.StartsWith("ALIGNV")
                    if (value.StartsWith("ALIGNV"))
                    {
                        int maxVert = int.MaxValue;
                        int minVert = int.MinValue;
                        for (int m = this.selected_controls.Count - 1; m >= 0; m--)
                        {
                            if (this.controls[this.selected_controls[m]].Location.Y < maxVert)
                            {
                                maxVert = this.controls[this.selected_controls[m]].Location.Y;
                            }
                            if (this.controls[this.selected_controls[m]].Location.Y > minVert)
                            {
                                minVert = this.controls[this.selected_controls[m]].Location.Y;
                            }
                        }
                        int centered = this.Grider((maxVert + minVert) / 2);
                        this.StartCacheHistory();
                        for (int n = this.selected_controls.Count - 1; n >= 0; n--)
                        {
                            this.controls[this.selected_controls[n]].Location = new Point(this.controls[this.selected_controls[n]].Location.X, centered);
                        }
                        //this.ContinueHistory(UnReDoType.Control);
                        return;
                    }
                    #endregion
                    #region value.StartsWith("ALIGNH")
                    if (value.StartsWith("ALIGNH"))
                    {
                        int minHoriz = int.MaxValue;
                        int maxHoriz = int.MinValue;
                        for (int m = this.selected_controls.Count - 1; m >= 0; m--)
                        {
                            if (this.controls[this.selected_controls[m]].Location.X < minHoriz)
                            {
                                minHoriz = this.controls[this.selected_controls[m]].Location.X;
                            }
                            if (this.controls[this.selected_controls[m]].Location.X > maxHoriz)
                            {
                                maxHoriz = this.controls[this.selected_controls[m]].Location.X;
                            }
                        }
                        int centered = this.Grider((minHoriz + maxHoriz) / 2);
                        this.StartCacheHistory();
                        for (int n = this.selected_controls.Count - 1; n >= 0; n--)
                        {
                            this.controls[this.selected_controls[n]].Location = new Point(centered, this.controls[this.selected_controls[n]].Location.Y);
                        }
                        //this.ContinueHistory(UnReDoType.Control);
                        return;
                    }
                    #endregion
                }
                else
                {
                    #region "DELETE" "CUT"
                    if ((value == "DELETE") || (value == "CUT"))
                    {
                        return;
                    }
                    #endregion
                    #region value == "LEFT"
                    if (value == "LEFT")
                    {
                        int newX = this.MousePlace.X - this.gridSize;
                        if (this.Grider(newX) >= 0)
                        {
                            if (this.SetInputInControl(new Point(newX, this.MousePlace.Y), false) == -1)
                            {
                                this.MousePlace = new Point(this.Grider(newX), this.Grider(this.MousePlace.Y));
                                this.CanvasResizer();
                                base.Invalidate(new Rectangle(this.MousePlace.X - this.Xbar.Value, this.MousePlace.Y - this.Ybar.Value, 2 * this.gridSize, this.gridSize));
                            }
                        }
                        return;
                    }
                    #endregion
                    #region value == "RIGHT"
                    if (value == "RIGHT")
                    {
                        int newX = this.MousePlace.X + this.gridSize;
                        if (this.SetInputInControl(new Point(newX, this.MousePlace.Y), true) == -1)
                        {
                            this.MousePlace = new Point(this.Grider(newX), this.Grider(this.MousePlace.Y));
                            this.CanvasResizer();
                            base.Invalidate(new Rectangle((this.MousePlace.X - this.Xbar.Value) - this.gridSize, this.MousePlace.Y - this.Ybar.Value, 2 * this.gridSize, this.gridSize));
                        }
                        return;
                    }
                    #endregion
                    #region value == "UP"
                    if (value == "UP")
                    {
                        int newY = this.MousePlace.Y - this.gridSize;
                        if (this.Grider(newY) >= 0)
                        {
                            if (this.SetInputInControl(new Point(this.MousePlace.X, newY), false) == -1)
                            {
                                this.MousePlace = new Point(this.Grider(this.MousePlace.X), this.Grider(newY));
                                this.CanvasResizer();
                                base.Invalidate(new Rectangle(this.MousePlace.X - this.Xbar.Value, this.MousePlace.Y - this.Ybar.Value, this.gridSize, 2 * this.gridSize));
                            }
                        }
                        return;
                    }
                    #endregion
                    #region value == "DOWN"
                    if (value == "DOWN")
                    {
                        int newY = this.MousePlace.Y + this.gridSize;
                        if (this.SetInputInControl(new Point(this.MousePlace.X, newY), true) == -1)
                        {
                            this.MousePlace = new Point(this.Grider(this.MousePlace.X), this.Grider(newY));
                            this.CanvasResizer();
                            base.Invalidate(new Rectangle(this.MousePlace.X - this.Xbar.Value, (this.MousePlace.Y - this.Ybar.Value) - this.gridSize, this.gridSize, 2 * this.gridSize));
                        }
                        return;
                    }
                    #endregion
                    #region "\b" "BACK"
                    if ((value == "\b") || (value == "BACK"))
                    {
                        if ((this.MousePlace.Y - this.gridSize) >= 0)
                        {
                            this.ShiftY(-this.gridSize, this.MousePlace.Y);
                            this.MousePlace = new Point(this.Grider(this.MousePlace.X), this.Grider(this.MousePlace.Y - this.gridSize));
                            this.CanvasResizer();
                            base.Invalidate(new Rectangle(this.MousePlace.X - this.Xbar.Value, this.MousePlace.Y - this.Ybar.Value, this.gridSize, 2 * this.gridSize));
                        }
                        return;
                    }
                    #endregion
                    #region "\r" "ENTER"
                    else if ((value == "\r") || (value == "ENTER"))
                    {
                        this.ShiftY(this.gridSize, this.MousePlace.Y);
                        this.MousePlace = new Point(this.Grider(this.MousePlace.X), this.Grider(this.MousePlace.Y + this.gridSize));
                        this.Ybar.Maximum += this.gridSize;
                        base.Invalidate(new Rectangle(this.MousePlace.X - this.Xbar.Value, (this.MousePlace.Y - this.Ybar.Value) - this.gridSize, this.gridSize, 2 * this.gridSize));
                        return;
                    }
                    #endregion
                    #region value == "PASTE"
                    if (value == "PASTE")
                    {
                        if (this.ClipboardGetData())
                        {
                            return;
                        }
                        string s = this.ClipboardGetText();
                        Bitmap imageFileStream = this.ClipboardGetImage();
                        if (s != null)
                        {
                            TextControl control = new TextControl();
                            this.ElementCreater(control, new Point(this.MousePlace.X, this.MousePlace.Y), true, true, true, true);
                            control.Text = s;
                            control.Action("");
                            this.ScrollControlToScreenBoundsSmooth(control);
                            return;
                        }
                        if (imageFileStream != null)
                        {
                            /*PictureControl control13 = new PictureControl();
                            this.ElementCreater(control13, new Point(this.MousePlace.X, this.MousePlace.Y), true, true, true, true);
                            control13.LoadImageBitmap(imageFileStream);*/
                            return;
                        }
                    }
                    #endregion
                    if (value != "ALIGNV" && value != "ALIGNH")
                    {
                        this.Insert("INSERTTEXT");
                        this.controls[this.current].Action(value);
                        return;
                    }
                }
            }
            else
            {
                #region value.StartsWith("TOGREEK")
                if (value.StartsWith("TOGREEK"))
                {
                    try
                    {
                        if (this.controls[this.current] is TextControl)
                        {
                            TextControl control = (TextControl)this.controls[this.current];
                            if (control.watch > 0)
                            {
                                control.Text = control.Text.Insert(control.watch - 1, this.ToGreek(control.Text[control.watch - 1])).Remove(control.watch, 1);
                                control.InDate = false;
                                control.PrePainter();
                                control.RePainter();
                            }
                        }
                    }
                    catch (Exception exception)
                    {
                        MessageBox.Show(exception.Message);
                    }
                    return;
                }
                #endregion
                #region value == "PASTE"
                if (value == "PASTE")
                {
                    return;
                }
                #endregion
                #region value == "COPY"
                if (value == "COPY")
                {
                    return;
                }
                #endregion
                #region value == "CUT"
                if (value == "CUT")
                {
                    this.controls[this.current].Action(value);
                    return;
                }
                #endregion
                else
                {
                    this.controls[this.current].Action(value);
                    this.ScrollControlToScreenBoundsSmooth(this.controls[this.current]);
                    this.DoINeedToDeleteElement(this.current);
                    return;
                }
            }
        }

        private void OldInsertString(string value)
        {
            int num3;
            string str5;
            if (value.StartsWith("mouse|"))
            {
                string[] strArray = value.Split(new char[] { '|' });
                int num = Convert.ToInt32(strArray[1]);
                int num2 = Convert.ToInt32(strArray[2]);
                this.OnMouseDown(new MouseEventArgs(MouseButtons.Left, 1, num, num2, 0));
                this.OnMouseUp(new MouseEventArgs(MouseButtons.Left, 1, num, num2, 0));
                return;
            }
            if (!value.StartsWith("insert|"))
            {
                if (value != "TAB" && value != "\t" &&
                    ((this.pageState != CanvasEditStatus.ReadOnly && this.current == -1) || value != "DOWN"))
                {
                    if (value == "BTAB" || value == "\t" ||
                        ((this.pageState == CanvasEditStatus.ReadOnly || this.current != -1) && value == "UP"))
                    {
                        if (this.controls.Count > 0)
                        {
                            int num7 = this.controls.Count - 1;
                            for (int j = this.current - 1; j >= 0; j--)
                            {
                                if (!(this.controls[j] is TextControl) || (((TextControl)this.controls[j]).Text != "●"))
                                {
                                    num7 = j;
                                    break;
                                }
                            }
                            int num9 = ((this.controls[num7].Location.X - this.Xbar.Value) + (this.gridSize / 2)) + 1;
                            int num10 = ((this.controls[num7].Location.Y - this.Ybar.Value) + (this.gridSize / 2)) + 1;
                            this.OnMouseDown(new MouseEventArgs(MouseButtons.Left, 1, num9, num10, 0));
                            this.OnMouseUp(new MouseEventArgs(MouseButtons.Middle, 1, num9, num10, 0));
                            if (this.current != -1)
                            {
                                if ((num9 < 0) || ((num9 + this.controls[this.current].Size.Width) > this.SheetSize.Width))
                                {
                                    this.Xbar.Value += num9;
                                }
                                if ((num10 < 0) || ((num10 + this.controls[this.current].Size.Height) > this.SheetSize.Height))
                                {
                                    this.Ybar.Value += num10;
                                }
                            }
                        }
                        return;
                    }
                    if (value == "PAGEUP")
                    {
                        if ((this.Ybar.Value - this.Ybar.LargeChange) >= 0)
                        {
                            this.Ybar.Value -= this.Grider(this.Ybar.LargeChange);
                            return;
                        }
                        this.Ybar.Value = 0;
                        return;
                    }
                    if (value == "PAGEDOWN")
                    {
                        if ((this.Ybar.Value + this.Ybar.LargeChange) <= (this.Ybar.Maximum - this.Ybar.LargeChange))
                        {
                            this.Ybar.Value += this.Grider(this.Ybar.LargeChange);
                            return;
                        }
                        this.Ybar.Value = this.Grider(this.Ybar.Maximum - this.Ybar.LargeChange);
                        return;
                    }
                    if (value == "HOME")
                    {
                        this.Ybar.Value = 0;
                        return;
                    }
                    if (value == "END")
                    {
                        this.Ybar.Value = this.Ybar.Maximum - this.Ybar.LargeChange;
                        return;
                    }
                    if ((this.pageState == CanvasEditStatus.ReadOnly) && ((value == "ENTER") || (value == "\r")))
                    {
                        if (((this.current != -1) && (this.controls[this.current] is TextControl)) && (((TextControl)this.controls[this.current]).link != null))
                        {
                            this.controls[this.current].LinkClick();
                        }
                    }
                    else
                    {
                        if (((this.pageState == CanvasEditStatus.ReadOnly) && ((value == "BACK") || (value == "\b"))) && (this.backFile != ""))
                        {
                            this.LinkOpener(this.backFile);
                            return;
                        }
                        if (value == "UNDO")
                        {
                            this.UnDo();
                            return;
                        }
                        if (value == "REDO")
                        {
                            this.ReDo();
                            return;
                        }
                        if (value == "MBH")
                        {
                            this.LinkOpener(this.homeFile);
                            return;
                        }
                    }
                    if (value == "\x001b")
                    {
                        if (this.IsPickedUp)
                        {
                            this.IsPickedUp = false;
                            this.mousedown = false;
                            for (int k = this.selected_controls.Count - 1; k >= 0; k--)
                            {
                                base.Invalidate(new Rectangle(this.selected[k].Left, this.selected[k].Top, this.selected[k].Right - this.selected[k].Left, this.selected[k].Bottom - this.selected[k].Top));
                            }
                            return;
                        }
                        if (this.selected_controls.Count > 0)
                        {
                            this.current = -1;
                            this.SelectControls(SelectionType.None);
                        }
                        return;
                    }
                    if (((((this.pageState != CanvasEditStatus.Editable) && (value != "COPY")) && ((value != "UP") && (value != "DOWN"))) && (((value != "RIGHT") && (value != "LEFT")) && ((value != "CRIGHT") && (value != "CLEFT")))) && ((value != "SRIGHT") && (value != "SLEFT")))
                    {
                        return;
                    }
                    if (this.current == -1 && (value == "{" || value == "}" || value == ")" || value == "#" || value == "\""))
                    {
                        this.Insert("INSERTTEXT");
                        return;
                    }
                    //if (value == "MB")
                    //{
                    //    this.LinkOpener(string.Concat(new object[] { LangSelection.ApplicationPath, "book", Path.DirectorySeparatorChar, "contents.sm" }));
                    //    return;
                    //}
                    if (value.StartsWith("PLOT"))
                    {
                        //if ((this.current != -1) && !(this.controls[this.current] is PlotControl))
                        //{
                        //    return;
                        //}
                        if (((this.current == -1) && (value != "PLOT3|0")) && (value != "PLOT3|1"))
                        {
                            return;
                        }
                    }
                    if ((value != "SELECTALL") || (this.current != -1))
                    {
                        if (value == "INSERTAREA")
                        {
                            /*if ((this.current == -1) || (this.selected_controls.Count > 0))
                            {
                                this.StartCacheHistory();
                                AreaControl control2 = new AreaControl();
                                control2.collapsed = false;
                                control2.top = true;
                                control2.Size = new Size(this.CanvasSize.Width, LangSelection.ScreenFactor(0x11));
                                this.ElementCreater(control2, new Point(this.Xbar.Value, this.MousePlace.Y), true, true, true, true);
                                control2.collapsedChanged += new CollapseStatusChanged(this.v1_collapsedChanged);
                                AreaControl control3 = new AreaControl();
                                control3.Size = new Size(this.CanvasSize.Width, LangSelection.ScreenFactor(0x11));
                                this.ElementCreater(control3, new Point(this.Xbar.Value, this.MousePlace.Y + 50), true, true, true, true);
                                control2.RePainter();
                                control3.RePainter();
                                this.ContinueHistory(UnReDoType.ControlAdd);
                            }*/
                            return;
                        }
                        if (value == "INSERTSEPARATOR")
                        {
                            if ((this.current == -1) || (this.selected_controls.Count > 0))
                            {
                                /*AreaControl control4 = new AreaControl();
                                control4.Size = new Size(this.CanvasSize.Width, LangSelection.ScreenFactor(0x11));
                                this.ElementCreater(control4, new Point(this.Xbar.Value, this.MousePlace.Y), true, true, true, true);
                                control4.collapsedChanged += new CollapseStatusChanged(this.v1_collapsedChanged);
                                control4.RePainter();*/
                            }
                            return;
                        }
                        if (value == "INSERTTEXT")
                        {
                            if ((this.current == -1) || (this.selected_controls.Count > 0))
                            {
                                TextControl control5 = new TextControl();
                                control5.Text = "";
                                this.ElementCreater(control5, new Point(this.MousePlace.X, this.MousePlace.Y), true, true, true, true);
                                control5.PrePainter();
                                control5.RePainter();
                                this.CanvasResizer(control5);
                                this.ScrollControlToScreenBoundsSmooth(control5);
                            }
                            return;
                        }
                        if (value == "INSERTPICTURE")
                        {
                            if ((this.current == -1) || (this.selected_controls.Count > 0))
                            {
                                /*PictureControl control6 = new PictureControl();
                                this.ElementCreater(control6, new Point(this.MousePlace.X, this.MousePlace.Y), true, true, true, true);
                                control6.PrePainter();
                                control6.RePainter();
                                this.CanvasResizer(control6);
                                this.ScrollControlToScreenBoundsSmooth(control6);*/
                            }
                            return;
                        }
                        if (value.StartsWith("INSERTPICB|"))
                        {
                            try
                            {
                                /*string imageFileName = value.Remove(0, 11);
                                PictureControl control7 = new PictureControl();
                                this.ElementCreater(control7, new Point(this.MousePlace.X, this.MousePlace.Y), true, true, true, true);
                                control7.LoadImage(imageFileName);
                                control7.PrePainter();
                                control7.RePainter();
                                this.CanvasResizer(control7);
                                this.ScrollControlToScreenBoundsSmooth(control7);*/
                            }
                            catch (Exception exception)
                            {
                                MessageBox.Show(exception.Message);
                            }
                            return;
                        }
                        if (value.StartsWith("ALIGNV"))
                        {
                            int maxVert = int.MaxValue;
                            int minVert = int.MinValue;
                            for (int m = this.selected_controls.Count - 1; m >= 0; m--)
                            {
                                if (this.controls[this.selected_controls[m]].Location.Y < maxVert)
                                {
                                    maxVert = this.controls[this.selected_controls[m]].Location.Y;
                                }
                                if (this.controls[this.selected_controls[m]].Location.Y > minVert)
                                {
                                    minVert = this.controls[this.selected_controls[m]].Location.Y;
                                }
                            }
                            int centered = this.Grider((maxVert + minVert) / 2);
                            this.StartCacheHistory();
                            //this.StartLocationChanging();
                            for (int n = this.selected_controls.Count - 1; n >= 0; n--)
                            {
                                this.controls[this.selected_controls[n]].Location = new Point(this.controls[this.selected_controls[n]].Location.X, centered);
                            }
                            //this.StopLocationChanging(false, null, -1);
                            //this.ContinueHistory(UnReDoType.Control);
                            return;
                        }
                        if (value.StartsWith("ALIGNH"))
                        {
                            int minHoriz = int.MaxValue;
                            int maxHoriz = int.MinValue;
                            for (int m = this.selected_controls.Count - 1; m >= 0; m--)
                            {
                                if (this.controls[this.selected_controls[m]].Location.X < minHoriz)
                                {
                                    minHoriz = this.controls[this.selected_controls[m]].Location.X;
                                }
                                if (this.controls[this.selected_controls[m]].Location.X > maxHoriz)
                                {
                                    maxHoriz = this.controls[this.selected_controls[m]].Location.X;
                                }
                            }
                            int centered = this.Grider((minHoriz + maxHoriz) / 2);
                            this.StartCacheHistory();
                            //this.StartLocationChanging();
                            for (int n = this.selected_controls.Count - 1; n >= 0; n--)
                            {
                                this.controls[this.selected_controls[n]].Location = new Point(centered, this.controls[this.selected_controls[n]].Location.Y);
                            }
                            //this.StopLocationChanging(false, null, -1);
                            //this.ContinueHistory(UnReDoType.Control);
                            return;
                        }
                        if (value.StartsWith("TOGREEK"))
                        {
                            try
                            {
                                /*if ((this.controls[this.current] is MathControl) || (this.controls[this.current] is PlotControl))
                                {
                                    MathControl control8 = (this.controls[this.current] is MathControl) ? ((MathControl) this.controls[this.current]) : ((PlotControl) this.controls[this.current]).math;
                                    if ((((control8.watch[0] >= 0) && (control8.watch[0] < control8.IMG.Length)) && ((control8.IMG[control8.watch[0]].Type == EquType.Operand) && (control8.watch[1] > -1))) && (control8.watch[1] < control8.IMG[control8.watch[0]].Text.Length))
                                    {
                                        control8.IMG[control8.watch[0]].Text = control8.IMG[control8.watch[0]].Text.Insert(control8.watch[1], this.ToGreek(control8.IMG[control8.watch[0]].Text[control8.watch[1]])).Remove(control8.watch[1] + 1, 1);
                                        control8.InDate = false;
                                        control8.PrePainter();
                                        control8.RePainter();
                                    }
                                }
                                else*/
                                if (this.controls[this.current] is TextControl)
                                {
                                    TextControl control9 = (TextControl)this.controls[this.current];
                                    if (control9.watch > 0)
                                    {
                                        control9.Text = control9.Text.Insert(control9.watch - 1, this.ToGreek(control9.Text[control9.watch - 1])).Remove(control9.watch, 1);
                                        control9.InDate = false;
                                        control9.PrePainter();
                                        control9.RePainter();
                                    }
                                }
                            }
                            catch (Exception exception2)
                            {
                                MessageBox.Show(exception2.Message);
                            }
                            return;
                        }
                        if ((((value == "INVERT") || (value == "EXPAND")) || ((value == "DET") || (value == "DIFF"))) || ((value == "CALCULATE") || (value == "SOLVE")))
                        {
                            bool flag = false;
                            /*if ((this.current == -1) || !(this.controls[this.current] is MathControl))
                            {
                                flag = false;
                            }
                            else
                            {
                                EquImage[] selectedItems = ((MathControl) this.controls[this.current]).GetSelectedItems();
                                EquImage[] sideElements = ((MathControl) this.controls[this.current]).GetSideElements();
                                EquImage[] imageArray4 = null;
                                if (selectedItems != null)
                                {
                                    int index = 0;
                                    string text = value.ToLower();
                                    try
                                    {
                                        this.eval.controls = this.controls;
                                        ParamWizard previouslyDefinedParams = this.eval.GetPreviouslyDefinedParams(this.current);
                                        Decision decision = new Decision(null);
                                        if ((value == "DIFF") || (value == "SOLVE"))
                                        {
                                            if (selectedItems.Length != 1)
                                            {
                                                MessageBox.Show(SSException.GetErrorText(Error.HighlightVariable), LangSelection.FTitle);
                                                return;
                                            }
                                            imageArray4 = new EquImage[sideElements.Length + 2];
                                            index = 0;
                                            while (index < sideElements.Length)
                                            {
                                                imageArray4[index] = new EquImage(sideElements[index]);
                                                index++;
                                            }
                                            imageArray4[index++] = new EquImage(selectedItems[0]);
                                            imageArray4[index] = new EquImage(text, EquType.Function, 2);
                                            if (value == "SOLVE")
                                            {
                                                imageArray4 = decision.NumericCalculation(imageArray4, previouslyDefinedParams);
                                            }
                                            if (value == "DIFF")
                                            {
                                                imageArray4 = decision.SymbolicCalculation(imageArray4, previouslyDefinedParams);
                                            }
                                        }
                                        else if (value == "EXPAND")
                                        {
                                            imageArray4 = decision.SymbolicEI(selectedItems, previouslyDefinedParams);
                                        }
                                        else if (value == "CALCULATE")
                                        {
                                            imageArray4 = decision.NumericCalculation(selectedItems, previouslyDefinedParams);
                                        }
                                        else
                                        {
                                            imageArray4 = new EquImage[selectedItems.Length + 1];
                                            index = 0;
                                            while (index < selectedItems.Length)
                                            {
                                                imageArray4[index] = new EquImage(selectedItems[index]);
                                                index++;
                                            }
                                            imageArray4[index] = new EquImage(text, EquType.Function, 1);
                                            imageArray4 = decision.AutoCalculation(imageArray4, previouslyDefinedParams);
                                        }
                                        MathControl control10 = new MathControl();
                                        control10.IMG = imageArray4;
                                        control10.PrePainter();
                                        this.ShiftY(control10.Size.Height, this.controls[this.current].Bottom);
                                        this.ElementCreater(control10, new Point(this.Grider(this.controls[this.current].Location.X), this.Grider(this.controls[this.current].Bottom + 4)), true, true, false, true);
                                        control10.RePainter();
                                    }
                                    catch (Exception exception3)
                                    {
                                        MessageBox.Show(exception3.Message, LangSelection.FTitle);
                                        return;
                                    }
                                    flag = true;
                                }
                            }
                            if (!flag)
                            {
                                MessageBox.Show(SSException.GetErrorText(Error.SelectExpression), LangSelection.FTitle);
                                return;
                            }*/
                            goto Label_2CD3;
                        }
                        if (this.selected_controls.Count > 0)
                        {
                            if ((value == "COPY") || (value == "CUT"))
                            {
                                this.ClipboardSetData();
                            }
                            if (((value == "\b") || (value == "BACK")) || ((value == "DELETE") || (value == "CUT")))
                            {
                                this.RemoveControls(this.selected_controls.ToArray());
                            }
                            else if (value != "COPY")
                            {
                                this.SelectControls(SelectionType.None);
                                this.current = -1;
                                this.Insert(value);
                            }
                            goto Label_2CD3;
                        }
                        if (this.current == -1)
                        {
                            if (value == "PASTE")
                            {
                                if (this.ClipboardGetData())
                                {
                                    return;
                                }
                                string str4 = this.ClipboardGetText();
                                Bitmap imageFileStream = this.ClipboardGetImage();
                                if (str4 != null)
                                {
                                    if (str4.IndexOfAny(new char[] { ' ', '\r', '\n' }) == -1)
                                    {
                                        try
                                        {
                                            /*str4 = str4.Replace(":=", "←").Replace(":", "←");
                                            MathControl control11 = new MathControl();
                                            this.ElementCreater(control11, new Point(this.MousePlace.X, this.MousePlace.Y), true, true, true, true);
                                            control11.IMG = new String2ArrayOfEquImage().Convert(str4);
                                            control11.watch[0] = control11.IMG.Length - 1;
                                            control11.watch[1] = (control11.IMG[control11.IMG.Length - 1].Type == EquType.Operand) ? (control11.IMG[control11.IMG.Length - 1].Text.Length - 1) : 0;
                                            control11.Action("");
                                            this.ScrollControlToScreenBoundsSmooth(control11);*/
                                            return;
                                        }
                                        catch
                                        {
                                            this.controls.RemoveAt(this.current);
                                        }
                                    }
                                    TextControl control12 = new TextControl();
                                    this.ElementCreater(control12, new Point(this.MousePlace.X, this.MousePlace.Y), true, true, true, true);
                                    control12.Text = str4;
                                    control12.Action("");
                                    this.ScrollControlToScreenBoundsSmooth(control12);
                                    return;
                                }
                                if (imageFileStream != null)
                                {
                                    /*PictureControl control13 = new PictureControl();
                                    this.ElementCreater(control13, new Point(this.MousePlace.X, this.MousePlace.Y), true, true, true, true);
                                    control13.LoadImageBitmap(imageFileStream);*/
                                    return;
                                }
                            }
                            else
                            {
                                if ((value == "DELETE") || (value == "CUT"))
                                {
                                    return;
                                }
                                if (value == "LEFT")
                                {
                                    int newX = this.MousePlace.X - this.gridSize;
                                    if (this.Grider(newX) >= 0)
                                    {
                                        if (this.SetInputInControl(new Point(newX, this.MousePlace.Y), false) == -1)
                                        {
                                            this.MousePlace = new Point(this.Grider(newX), this.Grider(this.MousePlace.Y));
                                            this.CanvasResizer();
                                            base.Invalidate(new Rectangle(this.MousePlace.X - this.Xbar.Value, this.MousePlace.Y - this.Ybar.Value, 2 * this.gridSize, this.gridSize));
                                        }
                                    }
                                    return;
                                }
                                if (value == "RIGHT")
                                {
                                    int newX = this.MousePlace.X + this.gridSize;
                                    if (this.SetInputInControl(new Point(newX, this.MousePlace.Y), true) == -1)
                                    {
                                        this.MousePlace = new Point(this.Grider(newX), this.Grider(this.MousePlace.Y));
                                        this.CanvasResizer();
                                        base.Invalidate(new Rectangle((this.MousePlace.X - this.Xbar.Value) - this.gridSize, this.MousePlace.Y - this.Ybar.Value, 2 * this.gridSize, this.gridSize));
                                    }
                                    return;
                                }
                                if (value == "UP")
                                {
                                    int newY = this.MousePlace.Y - this.gridSize;
                                    if (this.Grider(newY) >= 0)
                                    {
                                        if (this.SetInputInControl(new Point(this.MousePlace.X, newY), false) == -1)
                                        {
                                            this.MousePlace = new Point(this.Grider(this.MousePlace.X), this.Grider(newY));
                                            this.CanvasResizer();
                                            base.Invalidate(new Rectangle(this.MousePlace.X - this.Xbar.Value, this.MousePlace.Y - this.Ybar.Value, this.gridSize, 2 * this.gridSize));
                                        }
                                    }
                                    return;
                                }
                                if (value == "DOWN")
                                {
                                    int newY = this.MousePlace.Y + this.gridSize;
                                    if (this.SetInputInControl(new Point(this.MousePlace.X, newY), true) == -1)
                                    {
                                        this.MousePlace = new Point(this.Grider(this.MousePlace.X), this.Grider(newY));
                                        this.CanvasResizer();
                                        base.Invalidate(new Rectangle(this.MousePlace.X - this.Xbar.Value, (this.MousePlace.Y - this.Ybar.Value) - this.gridSize, this.gridSize, 2 * this.gridSize));
                                    }
                                    return;
                                }
                                if ((value == "\b") || (value == "BACK"))
                                {
                                    if ((this.MousePlace.Y - this.gridSize) >= 0)
                                    {
                                        this.ShiftY(-this.gridSize, this.MousePlace.Y);
                                        this.MousePlace = new Point(this.Grider(this.MousePlace.X), this.Grider(this.MousePlace.Y - this.gridSize));
                                        this.CanvasResizer();
                                        base.Invalidate(new Rectangle(this.MousePlace.X - this.Xbar.Value, this.MousePlace.Y - this.Ybar.Value, this.gridSize, 2 * this.gridSize));
                                    }
                                }
                                else if ((value == "\r") || (value == "ENTER"))
                                {
                                    this.ShiftY(this.gridSize, this.MousePlace.Y);
                                    this.MousePlace = new Point(this.Grider(this.MousePlace.X), this.Grider(this.MousePlace.Y + this.gridSize));
                                    this.Ybar.Maximum += this.gridSize;
                                    base.Invalidate(new Rectangle(this.MousePlace.X - this.Xbar.Value, (this.MousePlace.Y - this.Ybar.Value) - this.gridSize, this.gridSize, 2 * this.gridSize));
                                }
                                else if (((value != "=") && (value != "=/")) && ((value != "=_") && (value != "COPY")))
                                {
                                    BaseControl control14 = new BaseControl();
                                    if (value == "@")
                                    {
                                        value = "PLOT3|0";
                                    }
                                    if ((value == "PLOT3|0") || (value == "PLOT3|1"))
                                    {
                                        /*control14 = new PlotControl();
                                        if (LangSelection.Platform == LangSelection.PlatformType.PC)
                                        {
                                            control14.Size = new Size(LangSelection.ScreenFactor(350), LangSelection.ScreenFactor(0xe9));
                                        }
                                        else
                                        {
                                            int width;
                                            if (Screen.PrimaryScreen.Bounds.Width <= Screen.PrimaryScreen.Bounds.Height)
                                            {
                                                width = this.CanvasSize.Width;
                                            }
                                            else
                                            {
                                                width = this.CanvasSize.Height;
                                            }
                                            control14.Size = new Size(width, (int) (((double) width) / 1.5));
                                        }*/
                                    }
                                    else
                                    {
                                        /*if (((value == " ") && (this.controls[this.current] is MathControl)) && (((MathControl) this.controls[this.current]).IMG.Length == 1))
                    {
                        int startIndex = ((MathControl) this.controls[this.current]).watch[1] + 1;
                        value = ((MathControl) this.controls[this.current]).IMG[0].Text.Insert(startIndex, " ");
                        this.UndoRedoManager(this.controls[this.current], UnReDoType.ControlRemove, this.current);
                        this.controls[this.current] = new TextControl();
                        this.ElementCreater(this.controls[this.current], new Point(this.MousePlace.X, this.MousePlace.Y), false, false, false, true);
                        this.controls[this.current].Focus();
                    }*/
                                        control14 = new TextControl();
                                        //control14 = new MathControl();
                                        control14.Action(value);
                                    }
                                    this.ElementCreater(control14, new Point(this.MousePlace.X, this.MousePlace.Y), true, true, true, true);
                                    control14.Action("#");
                                    this.Insert(value);
                                    if ((value == "PLOT3|0") || (value == "PLOT3|1"))
                                    {
                                        //((PlotControl) control14).Reset();
                                        //((PlotControl) control14).ren.Refresh();
                                        //((PlotControl) control14).ren.Actualize();
                                        //((PlotControl) control14).ren.RePainter();
                                    }
                                }
                            }
                            goto Label_2CD3;
                        }
                        //if (LangSelection.Platform != LangSelection.PlatformType.Smartphone)
                        //{
                        //    goto Label_261F;
                        //}
                        str5 = value;
                        /*if (((value != "=") && (value != "—")) && (this.smartTimer.Enabled && (this.smartIndex == value)))
                        {
                            this.smartTimer_Tick(null, null);
                            switch (this.smartChar)
                            {
                                case "1":
                                    value = LangSelection.sep.ToString();
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case ".":
                                case ",":
                                case ";":
                                    value = "(";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "(":
                                    value = "sqrt(";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "sqrt(":
                                    value = "nthroot(";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "nthroot(":
                                    value = "int(";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "int(":
                                    value = "solve(";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "solve(":
                                    value = "1";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "2":
                                    value = "a";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "a":
                                    value = "b";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "b":
                                    value = "c";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "c":
                                    value = "2";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "3":
                                    value = "d";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "d":
                                    value = "e";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "e":
                                    value = "f";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "f":
                                    value = "3";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "4":
                                    value = "g";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "g":
                                    value = "h";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "h":
                                    value = "i";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "i":
                                    value = "4";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "5":
                                    value = "j";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "j":
                                    value = "k";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "k":
                                    value = "l";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "l":
                                    value = "5";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "6":
                                    value = "m";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "m":
                                    value = "n";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "n":
                                    value = "o";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "o":
                                    value = "6";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "7":
                                    value = "p";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "p":
                                    value = "q";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "q":
                                    value = "r";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "r":
                                    value = "s";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "s":
                                    value = "7";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "8":
                                    value = "t";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "t":
                                    value = "u";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "u":
                                    value = "v";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "v":
                                    value = "8";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "9":
                                    value = "w";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "w":
                                    value = "x";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "x":
                                    value = "y";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "y":
                                    value = "z";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "z":
                                    value = "9";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "+":
                                    value = "-";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "-":
                                    value = "*";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "*":
                                    value = "/";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "/":
                                    value = "^";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "^":
                                    value = "\x00b1";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "\x00b1":
                                    value = "!";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "!":
                                    value = "†";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;

                                case "†":
                                    value = "+";
                                    this.SmartInputUnDo();
                                    goto Label_25E8;
                            }
                        }
                        goto Label_25E8;*/
                    }
                    this.SelectControls(SelectionType.All);
                    goto Label_2CD3;
                }
                if (this.controls.Count <= 0)
                {
                    return;
                }
                num3 = 0;
                for (int i = this.current + 1; i < this.controls.Count; i++)
                {
                    if (!(this.controls[i] is TextControl) || (((TextControl)this.controls[i]).Text != "●"))
                    {
                        num3 = i;
                        break;
                    }
                }
            }
            else
            {
                try
                {
                    /*EquImage[] imageArray;
                    string str = value.Split(new char[] { '|' })[1];
                    imageArray = imageArray = new String2ArrayOfEquImage().Convert(str);
                    MathControl control = new MathControl();
                    this.ElementCreater(control, new Point(this.MousePlace.X, this.MousePlace.Y), true, true, true, true);
                    control.IMG = imageArray;
                    control.watch[0] = imageArray.Length - 1;
                    control.watch[1] = (imageArray[imageArray.Length - 1].Type == EquType.Operand) ? (imageArray[imageArray.Length - 1].Text.Length - 1) : 0;
                    control.Action("");*/
                }
                catch
                {
                    this.controls.RemoveAt(this.current);
                }
                return;
            }
            int x = ((this.controls[num3].Location.X - this.Xbar.Value) + (this.gridSize / 2)) + 1;
            int y = ((this.controls[num3].Location.Y - this.Ybar.Value) + (this.gridSize / 2)) + 1;
            this.OnMouseDown(new MouseEventArgs(MouseButtons.Left, 1, x, y, 0));
            this.OnMouseUp(new MouseEventArgs(MouseButtons.Middle, 1, x, y, 0));
            if (this.current != -1)
            {
                if ((x < 0) || ((x + this.controls[this.current].Size.Width) > this.SheetSize.Width))
                {
                    this.Xbar.Value += x;
                }
                if ((y < 0) || ((y + this.controls[this.current].Size.Height) > this.SheetSize.Height))
                {
                    this.Ybar.Value += y;
                }
            }
            return;
        Label_25E8:
            //this.smartIndex = str5;
            //this.smartChar = value;
            if (value == "\bs")
            {
                value = "\b";
            }
            else
            {
                this.StopHistory();
                //this.smartTimer.Enabled = true;
            }
        Label_261F:
            if ((value == "COPY") || (value == "CUT"))
            {
                /*if (this.controls[this.current] is MathControl)
                {
                    if (((MathControl) this.controls[this.current]).sel[0] == -1)
                    {
                        return;
                    }
                    this.ClipboardSetObject(new ArrayOfEquImage2String().Convert(((MathControl) this.controls[this.current]).GetSelectedItems()));
                }
                else if (this.controls[this.current] is PlotControl)
                {
                    if (((PlotControl) this.controls[this.current]).math.sel[0] == -1)
                    {
                        return;
                    }
                    this.ClipboardSetObject(new ArrayOfEquImage2String().Convert(((PlotControl) this.controls[this.current]).math.GetSelectedItems()));
                }
                else*/
                if (this.controls[this.current] is TextControl)
                {
                    if (((TextControl)this.controls[this.current]).sel[0] == -1)
                    {
                        return;
                    }
                    this.ClipboardSetObject(((TextControl)this.controls[this.current]).GetSelectedItems());
                }
                if (value == "COPY")
                {
                    return;
                }
                value = "\b";
            }
            else
            {
                if (value == "PASTE")
                {
                    try
                    {
                        string str6 = this.ClipboardGetText();
                        /*if (((this.controls[this.current] is MathControl) || (this.controls[this.current] is PlotControl)) && (str6.IndexOfAny(new char[] { ' ', '\r', '\n' }) == -1))
                        {
                            if (this.controls[this.current] is MathControl)
                            {
                                ((MathControl) this.controls[this.current]).Action(new String2ArrayOfEquImage().Convert(str6));
                            }
                            if (this.controls[this.current] is PlotControl)
                            {
                                ((PlotControl) this.controls[this.current]).math.Action(new String2ArrayOfEquImage().Convert(str6));
                            }
                        }
                        else*/
                        if (this.controls[this.current] is TextControl)
                        {
                            this.controls[this.current].Action(str6);
                        }
                        goto Label_2B89;
                    }
                    catch
                    {
                        goto Label_2B89;
                    }
                }
                if (value == "SELECTALL")
                {
                    int[] numArray;
                    /*if (this.controls[this.current] is MathControl)
                    {
                        MathControl control15 = (MathControl) this.controls[this.current];
                        numArray = new int[2];
                        numArray[1] = control15.IMG.Length - 1;
                        control15.sel = numArray;
                        control15.RePainter();
                        return;
                    }
                    if (this.controls[this.current] is PlotControl)
                    {
                        PlotControl control16 = (PlotControl) this.controls[this.current];
                        numArray = new int[2];
                        numArray[1] = control16.math.IMG.Length - 1;
                        control16.math.sel = numArray;
                        control16.math.RePainter();
                        return;
                    }*/
                    if (this.controls[this.current] is TextControl)
                    {
                        TextControl control17 = (TextControl)this.controls[this.current];
                        numArray = new int[2];
                        numArray[1] = control17.Text.Length;
                        control17.sel = numArray;
                        control17.Action("");
                        return;
                    }
                }
                else
                {
                    /*if (((value == "\r") || (value == "ENTER")) && ((((this.controls[this.current] is TextControl) && !LangSelection.ctrlKeyPressed) && (!LangSelection.shiftKeyPressed && (this.selStatus == 0))) || ((this.controls[this.current] is AreaControl) || (this.controls[this.current] is PictureControl))))
                    {
                        this.ControlUnfocus();
                        return;
                    }
                    if (((value == " ") && (this.controls[this.current] is MathControl)) && (((MathControl) this.controls[this.current]).IMG.Length == 1))
                    {
                        int startIndex = ((MathControl) this.controls[this.current]).watch[1] + 1;
                        value = ((MathControl) this.controls[this.current]).IMG[0].Text.Insert(startIndex, " ");
                        this.UndoRedoManager(this.controls[this.current], UnReDoType.ControlRemove, this.current);
                        this.controls[this.current] = new TextControl();
                        this.ElementCreater(this.controls[this.current], new Point(this.MousePlace.X, this.MousePlace.Y), false, false, false, true);
                        this.controls[this.current].Focus();
                    }*/
                }
            }
        Label_2B89:
            if (value == "=/")
            {
                //if (this.controls[this.current] is MathControl)
                //{
                //    ((MathControl) this.controls[this.current]).fraction_type = FractionType.Fraction;
                //    this.controls[this.current].Action("=");
                //}
            }
            else if (value == "=_")
            {
                //if (this.controls[this.current] is MathControl)
                //{
                //    ((MathControl) this.controls[this.current]).fraction_type = FractionType.None;
                //    this.controls[this.current].Action("=");
                //}
            }
            else if (value != "PASTE")
            {
                //if ((value == "=") && (this.controls[this.current] is MathControl))
                //{
                //    ((MathControl) this.controls[this.current]).fraction_type = FractionType.Undefined;
                //}
                //this.controls[this.current].Action(value);
            }
            if (this.current != -1)
            {
                //this.ScrollControlToScreenBoundsSmooth(this.controls[this.current]);
            }
        Label_2CD3:
            if (this.current != -1)
            {
                this.DoINeedToDeleteElement(this.current);
            }
        }

        /*public static EquImage[] PostfixToPrefix(EquImage[] value)
        {
            EquImage[][] imageArray = new EquImage[value.Length][];
            int ind = 0;
            for (int i = 0; i < value.Length; i++)
            {
                switch (value[i].Type)
                {
                    case EquType.Function:
                    case EquType.Operator:
                    case EquType.Bracket:
                    {
                        EquImage[] imageArray2 = MergeManyArrayPrefix(imageArray, ind, value[i].ChildCount);
                        imageArray2[0] = value[i];
                        ind -= value[i].ChildCount;
                        imageArray[ind] = imageArray2;
                        ind++;
                        break;
                    }
                    case EquType.Operand:
                        imageArray[ind] = new EquImage[] { value[i] };
                        ind++;
                        break;
                }
            }
            return imageArray[ind - 1];
        }*/

        /*public static EquImage[] PrefixToPostfix(EquImage[] value)
        {
            EquImage[][] imageArray = new EquImage[value.Length][];
            int ind = 0;
            for (int i = value.Length - 1; i >= 0; i--)
            {
                switch (value[i].Type)
                {
                    case EquType.Function:
                    case EquType.Operator:
                    case EquType.Bracket:
                    {
                        EquImage[] imageArray2 = MergeManyArrayPostfix(imageArray, ind, value[i].ChildCount);
                        imageArray2[imageArray2.Length - 1] = value[i];
                        ind -= value[i].ChildCount;
                        imageArray[ind] = imageArray2;
                        ind++;
                        break;
                    }
                    case EquType.Operand:
                        imageArray[ind] = new EquImage[] { value[i] };
                        ind++;
                        break;
                }
            }
            return imageArray[ind - 1];
        }*/

        private void PreSelect(BaseControl control, Point e)
        {
            int count = this.selected_controls.Count;
            this.selected = new Rectangle[count];
            Rectangle rect = new Rectangle();
            rect.X = control.Location.X;
            rect.Y = control.Location.Y;
            rect.Width = control.Size.Width;
            rect.Height = control.Size.Height;
            int index = 0;
            for(int i = 0; i<this.controls.Count;i++)
            {
                BaseControl control2 = this.controls[i];
                if (this.controls[i].Selected)
                {
                    this.selected[index] = new Rectangle();
                    this.selected[index].X = control2.Location.X - this.Xbar.Value + 2;
                    this.selected[index].Width = control2.Size.Width - 4;
                    this.selected[index].Y = control2.Location.Y  - this.Ybar.Value + 2;
                    this.selected[index].Height = control2.Size.Height - 4;
                    if (this.selected[index].Left < rect.Left)
                    {
                        rect.X = this.selected[index].Left;
                    }
                    if (this.selected[index].Right > rect.Right)
                    {
                        rect.Width = this.selected[index].Right- rect.Left;
                    }
                    if (this.selected[index].Top < rect.Top)
                    {
                        rect.Y = this.selected[index].Y;
                    }
                    if (this.selected[index].Bottom > rect.Bottom)
                    {
                        rect.Height = this.selected[index].Bottom - rect.Top;
                    }
                    index++;
                }
            }
            this.vid1 = new Point(e.X - this.selected[count - 1].Left - this.Xbar.Value, 
                e.Y - this.selected[count - 1].Top - this.Ybar.Value);
            this.vid2 = new Point(e.X - rect.Left - this.Xbar.Value, e.Y - rect.Top - this.Ybar.Value);
        }

        private void ReCalc()
        {
            this.ReCalc(0);
        }

        private void ReCalc(int startIndex)
        {
            //this.ReCalc(startIndex, this.controls.Count - 1);
        }

        private void ReCalc(int startIndex, int endIndex)
        {
            //if (LangSelection.autoReCalc)
            //{
                //this.ReCalcInThread(startIndex, endIndex);
            //}
        }

        public void ReCalcInThread(int startIndex, int endIndex)
        {
            /*if ((this.pageState == CanvasEditStatus.Editable) && (this.evalThread == null))
            {
                this.eval.controls = this.controls;
                this.eval.startIndex = startIndex;
                this.eval.endIndex = endIndex;
                this.evalThread = new Thread(new ThreadStart(this.eval.ReEvaluate));
                this.evalThread.Name = "Evaluation";
                this.evalThread.IsBackground = true;
                this.evalEnd = this.evalStart = DateTime.Now;
                this.pageState = CanvasEditStatus.Calculation;
                this.PageStatusManager();
                this.evalThread.Start();
            }*/
        }

        private void RectangleDrawing(Graphics g, Rectangle rect)
        {
            g.DrawRectangle(new Pen(Color.FromArgb(0x33, 0x99, 0xff)), rect.X, rect.Y, rect.Width, rect.Height);
        }

        /*private void RecurseFill(EquImage[] ei, int childrenCount, XmlElement node, XmlDocument doc)
        {
            do
            {
                this.currentPos++;
                XmlElement element = null;
                if (ei[this.currentPos].Type == EquType.Operand)
                {
                    if (ei[this.currentPos].Text == "#")
                    {
                        element = doc.CreateElement("ml:placeholder", this.uri2);
                    }
                    else if (ei[this.currentPos].Text == "i")
                    {
                        element = doc.CreateElement("ml:imag", this.uri2);
                        this.CreateXMLAttribute("symbol", "i", doc, element);
                        element.InnerText = "1";
                    }
                    else if (MathMethods.IsNumber(ei[this.currentPos].Text))
                    {
                        element = doc.CreateElement("ml:real", this.uri2);
                        element.InnerText = ei[this.currentPos].Text.Replace(LangSelection.sep, '.');
                    }
                    else
                    {
                        element = doc.CreateElement("ml:id", this.uri2);
                        this.CreateXMLAttribute("xml:space", "preserve", doc, element);
                        element.InnerText = ei[this.currentPos].Text;
                    }
                    node.AppendChild(element);
                }
                else if (ei[this.currentPos].Type == EquType.Operator)
                {
                    if (ei[this.currentPos].Text == "=")
                    {
                        element = doc.CreateElement("ml:eval", this.uri2);
                        this.CreateXMLAttribute("placeholderMultiplicationStyle", "default", doc, element);
                        node.AppendChild(element);
                        this.RecurseFill(ei, 1, element, doc);
                        XmlElement newChild = doc.CreateElement("result", this.uri2);
                        element.AppendChild(newChild);
                        this.RecurseFill(ei, 1, newChild, doc);
                    }
                    else if (ei[this.currentPos].Text == "—")
                    {
                        element = doc.CreateElement("ml:symEval", this.uri2);
                        this.CreateXMLAttribute("style", "default", doc, element);
                        this.CreateXMLAttribute("hide-keywords", "false", doc, element);
                        this.CreateXMLAttribute("hide-lhs", "false", doc, element);
                        node.AppendChild(element);
                        this.RecurseFill(ei, 1, element, doc);
                        XmlElement element3 = doc.CreateElement("ml:symResult", this.uri2);
                        element.AppendChild(element3);
                        this.RecurseFill(ei, 1, element3, doc);
                    }
                    else if ((ei[this.currentPos].Text == "←") || (ei[this.currentPos].Text == ":"))
                    {
                        element = doc.CreateElement("ml:define", this.uri2);
                        node.AppendChild(element);
                        this.RecurseFill(ei, ei[this.currentPos].ChildCount, element, doc);
                    }
                    else
                    {
                        element = doc.CreateElement("ml:apply", this.uri2);
                        if (ei[this.currentPos].Text == "$")
                        {
                            element.AppendChild(doc.CreateElement("ml:unknownOp", this.uri2));
                        }
                        else if (ei[this.currentPos].Text == "≡")
                        {
                            element.AppendChild(doc.CreateElement("ml:equal", this.uri2));
                        }
                        else if (ei[this.currentPos].Text == "<")
                        {
                            element.AppendChild(doc.CreateElement("ml:lessThan", this.uri2));
                        }
                        else if (ei[this.currentPos].Text == ">")
                        {
                            element.AppendChild(doc.CreateElement("ml:greaterThan", this.uri2));
                        }
                        else if (ei[this.currentPos].Text == "≤")
                        {
                            element.AppendChild(doc.CreateElement("ml:lessOrEqual", this.uri2));
                        }
                        else if (ei[this.currentPos].Text == "≥")
                        {
                            element.AppendChild(doc.CreateElement("ml:greaterOrEqual", this.uri2));
                        }
                        else if (ei[this.currentPos].Text == "≠")
                        {
                            element.AppendChild(doc.CreateElement("ml:notEqual", this.uri2));
                        }
                        else if (ei[this.currentPos].Text == "~")
                        {
                            element.AppendChild(doc.CreateElement("ml:not", this.uri2));
                        }
                        else if (ei[this.currentPos].Text == "&")
                        {
                            element.AppendChild(doc.CreateElement("ml:and", this.uri2));
                        }
                        else if (ei[this.currentPos].Text == "|")
                        {
                            element.AppendChild(doc.CreateElement("ml:or", this.uri2));
                        }
                        else if (ei[this.currentPos].Text == "\x00a4")
                        {
                            element.AppendChild(doc.CreateElement("ml:xor", this.uri2));
                        }
                        else if (ei[this.currentPos].Text == "!")
                        {
                            element.AppendChild(doc.CreateElement("ml:factorial", this.uri2));
                        }
                        else if (ei[this.currentPos].Text == "+")
                        {
                            element.AppendChild(doc.CreateElement("ml:plus", this.uri2));
                        }
                        else if (ei[this.currentPos].Text == "-")
                        {
                            element.AppendChild(doc.CreateElement((ei[this.currentPos].ChildCount == 2) ? "ml:minus" : "ml:neg", this.uri2));
                        }
                        else if (ei[this.currentPos].Text == "*")
                        {
                            element.AppendChild(doc.CreateElement("ml:mult", this.uri2));
                        }
                        else if (ei[this.currentPos].Text == "/")
                        {
                            element.AppendChild(doc.CreateElement("ml:div", this.uri2));
                        }
                        else if (ei[this.currentPos].Text == "^")
                        {
                            element.AppendChild(doc.CreateElement("ml:pow", this.uri2));
                        }
                        else
                        {
                            if (ei[this.currentPos].Text != "†")
                            {
                                throw new NotSupportedException();
                            }
                            element.AppendChild(doc.CreateElement("ml:crossProduct", this.uri2));
                        }
                        node.AppendChild(element);
                        this.RecurseFill(ei, ei[this.currentPos].ChildCount, element, doc);
                    }
                }
                else if (ei[this.currentPos].Type == EquType.Function)
                {
                    if (ei[this.currentPos].Text == Function.Mat)
                    {
                        element = doc.CreateElement("ml:matrix", this.uri2);
                        node.AppendChild(element);
                        this.RecurseFill(ei, ei[this.currentPos].ChildCount - 2, element, doc);
                        this.CreateXMLAttribute("rows", ei[++this.currentPos].Text, doc, element);
                        this.CreateXMLAttribute("cols", ei[++this.currentPos].Text, doc, element);
                    }
                    else if (ei[this.currentPos].Text == Function.Diff)
                    {
                        element = doc.CreateElement("ml:apply", this.uri2);
                        XmlElement element4 = doc.CreateElement("ml:derivative", this.uri2);
                        element.AppendChild(element4);
                        XmlElement element5 = doc.CreateElement("ml:lambda", this.uri2);
                        element.AppendChild(element5);
                        XmlElement element6 = doc.CreateElement("ml:boundVars", this.uri2);
                        element5.AppendChild(element6);
                        this.RecurseFill(ei, ei[this.currentPos].ChildCount - 1, element5, doc);
                        this.RecurseFill(ei, 1, element6, doc);
                        node.AppendChild(element);
                    }
                    else if (ei[this.currentPos].Text == Function.Range)
                    {
                        element = doc.CreateElement("ml:range", this.uri2);
                        node.AppendChild(element);
                        this.RecurseFill(ei, ei[this.currentPos].ChildCount, element, doc);
                    }
                    else
                    {
                        element = doc.CreateElement("ml:apply", this.uri2);
                        XmlElement element7 = null;
                        if (ei[this.currentPos].Text == Function.Abs)
                        {
                            element7 = doc.CreateElement("ml:absval", this.uri2);
                        }
                        else if (ei[this.currentPos].Text == Function.Sqrt)
                        {
                            element7 = doc.CreateElement("ml:sqrt", this.uri2);
                        }
                        else if (ei[this.currentPos].Text == Function.Nthroot)
                        {
                            element7 = doc.CreateElement("ml:nthRoot", this.uri2);
                        }
                        else if (ei[this.currentPos].Text == Function.Transpose)
                        {
                            element7 = doc.CreateElement("ml:transpose", this.uri2);
                        }
                        else if (ei[this.currentPos].Text == Function.Det)
                        {
                            element7 = doc.CreateElement("ml:determinant", this.uri2);
                        }
                        else
                        {
                            element7 = doc.CreateElement("ml:id", this.uri2);
                            this.CreateXMLAttribute("xml:space", "preserve", doc, element7);
                            element7.InnerText = ei[this.currentPos].Text;
                        }
                        element.AppendChild(element7);
                        node.AppendChild(element);
                        this.RecurseFill(ei, ei[this.currentPos].ChildCount, element, doc);
                    }
                }
                else
                {
                    if (ei[this.currentPos].Type != EquType.Bracket)
                    {
                        throw new NotSupportedException();
                    }
                    element = doc.CreateElement("ml:parens", this.uri2);
                    node.AppendChild(element);
                    this.RecurseFill(ei, ei[this.currentPos].ChildCount, element, doc);
                }
            }
            while (--childrenCount != 0);
        }*/

        /*private void RecurseParse(Collection<EquImage> array, XmlTextReader Reader, Stack<int> parentId)
        {
            while (Reader.Read())
            {
                Reader.MoveToContent();
                if ((Reader.NodeType == XmlNodeType.Element) && (Reader.Name == "result"))
                {
                    Reader.Skip();
                    return;
                }
                if ((Reader.NodeType == XmlNodeType.Element) && ((Reader.Name == "ml:symResult") || (Reader.Name == "resultFormat")))
                {
                    Reader.Skip();
                    return;
                }
                if ((Reader.NodeType == XmlNodeType.Element) && (((Reader.Name == "originRef") || (Reader.Name == "parentRef")) || (((Reader.Name == "comment") || (Reader.Name == "originComment")) || (Reader.Name == "contentHash"))))
                {
                    Reader.Skip();
                    goto Label_0C4B;
                }
                if ((Reader.NodeType == XmlNodeType.Element) && ((Reader.Name == "ml:apply") || (Reader.Name == "ml:function")))
                {
                    this.intoApplyTag = true;
                    this.RecurseParse(array, Reader, parentId);
                    goto Label_0C4B;
                }
                if ((Reader.NodeType == XmlNodeType.Element) && ((((Reader.Name == "ml:lambda") || (Reader.Name == "ml:sequence")) || ((Reader.Name == "ml:eval") || (Reader.Name == "ml:symEval"))) || ((Reader.Name == "ml:boundVars") || (Reader.Name == "ml:provenance"))))
                {
                    this.RecurseParse(array, Reader, parentId);
                    goto Label_0C4B;
                }
                if ((Reader.NodeType == XmlNodeType.EndElement) && ((((Reader.Name == "ml:apply") || (Reader.Name == "ml:matrix")) || ((Reader.Name == "ml:define") || (Reader.Name == "ml:parens"))) || ((Reader.Name == "ml:range") || (Reader.Name == "ml:function"))))
                {
                    parentId.Pop();
                    if (parentId.Count != 0)
                    {
                        EquImage local1 = array[parentId.Peek()];
                        local1.ChildCount++;
                    }
                    return;
                }
                if ((Reader.NodeType == XmlNodeType.EndElement) && (((Reader.Name == "math") || (Reader.Name == "ml:lambda")) || (((Reader.Name == "ml:sequence") || (Reader.Name == "ml:boundVars")) || (Reader.Name == "ml:provenance"))))
                {
                    return;
                }
                if ((Reader.NodeType == XmlNodeType.EndElement) && (Reader.Name == "ml:eval"))
                {
                    array.Add(new EquImage("#", EquType.Operand, 0));
                    array.InsertInto(0, new EquImage("=", EquType.Operator, 2));
                    return;
                }
                if ((Reader.NodeType == XmlNodeType.EndElement) && (Reader.Name == "ml:symEval"))
                {
                    array.Add(new EquImage("#", EquType.Operand, 0));
                    array.InsertInto(0, new EquImage("—", EquType.Operator, 2));
                    return;
                }
                if ((Reader.NodeType == XmlNodeType.Element) && (Reader.Name == "ml:matrix"))
                {
                    array.Add(new EquImage(Function.Mat, EquType.Function, 2));
                    parentId.Push(array.Count - 1);
                    array.Add(new EquImage(Reader.GetAttribute("rows"), EquType.Operand, 0));
                    array.Add(new EquImage(Reader.GetAttribute("cols"), EquType.Operand, 0));
                    this.RecurseParse(array, Reader, parentId);
                    goto Label_0C4B;
                }
                if ((Reader.NodeType == XmlNodeType.Element) && (Reader.Name == "ml:derivative"))
                {
                    array.Add(new EquImage("diff", EquType.Function, 0));
                    parentId.Push(array.Count - 1);
                    goto Label_0C4B;
                }
                if ((Reader.NodeType == XmlNodeType.Element) && (Reader.Name == "ml:range"))
                {
                    array.Add(new EquImage("range", EquType.Function, 0));
                    parentId.Push(array.Count - 1);
                    this.RecurseParse(array, Reader, parentId);
                    goto Label_0C4B;
                }
                if ((Reader.NodeType == XmlNodeType.Element) && (Reader.Name == "ml:define"))
                {
                    array.Add(new EquImage("←", EquType.Operator, 0));
                    parentId.Push(array.Count - 1);
                    this.RecurseParse(array, Reader, parentId);
                    goto Label_0C4B;
                }
                if ((Reader.NodeType == XmlNodeType.Element) && (Reader.Name == "ml:parens"))
                {
                    array.Add(new EquImage("(", EquType.Bracket, 0));
                    parentId.Push(array.Count - 1);
                    this.RecurseParse(array, Reader, parentId);
                    goto Label_0C4B;
                }
                if ((Reader.NodeType == XmlNodeType.Element) && (Reader.Name == "ml:real"))
                {
                    Reader.Read();
                    Reader.MoveToContent();
                    if (Reader.Value.StartsWith("-"))
                    {
                        array.Add(new EquImage("-", EquType.Operator, 1));
                    }
                    array.Add(new EquImage(Reader.Value.TrimStart(new char[] { '-' }).Replace('.', LangSelection.sep).Replace(',', LangSelection.sep), EquType.Operand, 0));
                    if (parentId.Count != 0)
                    {
                        EquImage local2 = array[parentId.Peek()];
                        local2.ChildCount++;
                    }
                    Reader.Read();
                    Reader.MoveToContent();
                    goto Label_0C4B;
                }
                if ((Reader.NodeType == XmlNodeType.Element) && (Reader.Name == "ml:imag"))
                {
                    Reader.Read();
                    Reader.MoveToContent();
                    if (Reader.Value.StartsWith("-"))
                    {
                        array.Add(new EquImage("-", EquType.Operator, 1));
                    }
                    string str = Reader.Value.TrimStart(new char[] { '-' });
                    if (str == "1")
                    {
                        array.Add(new EquImage("i", EquType.Operand, 0));
                    }
                    else
                    {
                        array.Add(new EquImage("*", EquType.Operator, 2));
                        array.Add(new EquImage(str.TrimStart(new char[] { '-' }).Replace('.', LangSelection.sep).Replace(',', LangSelection.sep), EquType.Operand, 0));
                        array.Add(new EquImage("i", EquType.Operand, 0));
                    }
                    if (parentId.Count != 0)
                    {
                        EquImage local3 = array[parentId.Peek()];
                        local3.ChildCount++;
                    }
                    Reader.Read();
                    Reader.MoveToContent();
                    goto Label_0C4B;
                }
                if ((Reader.NodeType == XmlNodeType.Element) && (Reader.Name == "ml:placeholder"))
                {
                    array.Add(new EquImage("#", EquType.Operand, 0));
                    if (parentId.Count != 0)
                    {
                        EquImage local4 = array[parentId.Peek()];
                        local4.ChildCount++;
                    }
                    goto Label_0C4B;
                }
                if ((Reader.NodeType == XmlNodeType.Element) && (Reader.Name == "ml:id"))
                {
                    Reader.Read();
                    if (!this.intoApplyTag)
                    {
                        array.Add(new EquImage(Reader.Value, EquType.Operand, 0));
                    }
                    else
                    {
                        array.Add(new EquImage(Reader.Value, EquType.Function, 0));
                    }
                    Reader.Read();
                    if (this.intoApplyTag)
                    {
                        goto Label_0C3D;
                    }
                    if (parentId.Count != 0)
                    {
                        EquImage local5 = array[parentId.Peek()];
                        local5.ChildCount++;
                    }
                    continue;
                }
                if ((Reader.NodeType == XmlNodeType.Element) && (Reader.Name == "ml:unknownOp"))
                {
                    array.Add(new EquImage("$", EquType.Operator, 0));
                }
                else if ((Reader.NodeType == XmlNodeType.Element) && (Reader.Name == "ml:equal"))
                {
                    array.Add(new EquImage("≡", EquType.Operator, 0));
                }
                else if ((Reader.NodeType == XmlNodeType.Element) && (Reader.Name == "ml:lessThan"))
                {
                    array.Add(new EquImage("<", EquType.Operator, 0));
                }
                else if ((Reader.NodeType == XmlNodeType.Element) && (Reader.Name == "ml:greaterThan"))
                {
                    array.Add(new EquImage(">", EquType.Operator, 0));
                }
                else if ((Reader.NodeType == XmlNodeType.Element) && (Reader.Name == "ml:lessOrEqual"))
                {
                    array.Add(new EquImage("≤", EquType.Operator, 0));
                }
                else if ((Reader.NodeType == XmlNodeType.Element) && (Reader.Name == "ml:greaterOrEqual"))
                {
                    array.Add(new EquImage("≥", EquType.Operator, 0));
                }
                else if ((Reader.NodeType == XmlNodeType.Element) && (Reader.Name == "ml:notEqual"))
                {
                    array.Add(new EquImage("≠", EquType.Operator, 0));
                }
                else if ((Reader.NodeType == XmlNodeType.Element) && (Reader.Name == "ml:not"))
                {
                    array.Add(new EquImage("~", EquType.Operator, 0));
                }
                else if ((Reader.NodeType == XmlNodeType.Element) && (Reader.Name == "ml:and"))
                {
                    array.Add(new EquImage("&", EquType.Operator, 0));
                }
                else if ((Reader.NodeType == XmlNodeType.Element) && (Reader.Name == "ml:or"))
                {
                    array.Add(new EquImage("|", EquType.Operator, 0));
                }
                else if ((Reader.NodeType == XmlNodeType.Element) && (Reader.Name == "ml:xor"))
                {
                    array.Add(new EquImage("\x00a4", EquType.Operator, 0));
                }
                else if ((Reader.NodeType == XmlNodeType.Element) && (Reader.Name == "ml:factorial"))
                {
                    array.Add(new EquImage("!", EquType.Operator, 0));
                }
                else if ((Reader.NodeType == XmlNodeType.Element) && (Reader.Name == "ml:plus"))
                {
                    array.Add(new EquImage("+", EquType.Operator, 0));
                }
                else if ((Reader.NodeType == XmlNodeType.Element) && ((Reader.Name == "ml:minus") || (Reader.Name == "ml:neg")))
                {
                    array.Add(new EquImage("-", EquType.Operator, 0));
                }
                else if ((Reader.NodeType == XmlNodeType.Element) && (Reader.Name == "ml:mult"))
                {
                    array.Add(new EquImage("*", EquType.Operator, 0));
                }
                else if ((Reader.NodeType == XmlNodeType.Element) && (Reader.Name == "ml:div"))
                {
                    array.Add(new EquImage("/", EquType.Operator, 0));
                }
                else if ((Reader.NodeType == XmlNodeType.Element) && (Reader.Name == "ml:pow"))
                {
                    array.Add(new EquImage("^", EquType.Operator, 0));
                }
                else if ((Reader.NodeType == XmlNodeType.Element) && (Reader.Name == "ml:crossProduct"))
                {
                    array.Add(new EquImage("†", EquType.Operator, 0));
                }
                else if ((Reader.NodeType == XmlNodeType.Element) && (Reader.Name == "ml:absval"))
                {
                    array.Add(new EquImage(Function.Abs, EquType.Function, 0));
                }
                else if ((Reader.NodeType == XmlNodeType.Element) && (Reader.Name == "ml:sqrt"))
                {
                    array.Add(new EquImage(Function.Sqrt, EquType.Function, 0));
                }
                else if ((Reader.NodeType == XmlNodeType.Element) && (Reader.Name == "ml:nthRoot"))
                {
                    array.Add(new EquImage(Function.Nthroot, EquType.Function, 0));
                }
                else if ((Reader.NodeType == XmlNodeType.Element) && (Reader.Name == "ml:transpose"))
                {
                    array.Add(new EquImage(Function.Transpose, EquType.Function, 0));
                }
                else if ((Reader.NodeType == XmlNodeType.Element) && (Reader.Name == "ml:determinant"))
                {
                    array.Add(new EquImage(Function.Det, EquType.Function, 0));
                }
                else
                {
                    this.intoApplyTag = false;
                    throw new NotSupportedException();
                }
            Label_0C3D:
                parentId.Push(array.Count - 1);
            Label_0C4B:
                this.intoApplyTag = false;
            }
        }*/

        public void ReDo()
        {
            /*if ((this.UnReDO.Count > (this.UnReDoPoint + 1)) && (this.UnReDoMaximum > this.UnReDoPoint))
            {
                this.UnReDoPoint++;
                if (this.UnReDO[this.UnReDoPoint].type == UnReDoType.Control)
                {
                    this.UnReStateControl(false);
                }
                else if (this.UnReDO[this.UnReDoPoint].type == UnReDoType.ControlAdd)
                {
                    this.UnReAddControls();
                }
                else if (this.UnReDO[this.UnReDoPoint].type == UnReDoType.ControlRemove)
                {
                    this.UnReRemoveControls();
                }
                this.UnReFocusSetter(this.UnReDO[this.UnReDoPoint].current);
            }*/
        }

        private void RemoveControls(int[] controlsIndeces)
        {
            BaseControl[] controlArray = new BaseControl[controlsIndeces.Length];
            bool flag = false;
            Rectangle rc = new Rectangle();
            for (int i = controlsIndeces.Length - 1; i >= 0; i--)
            {
                BaseControl control = this.controls[controlsIndeces[i]];
                rc = new Rectangle(control.Location.X - this.Xbar.Value, control.Location.Y - this.Ybar.Value, control.Size.Width, control.Size.Height);
                //if (!flag && Evaluation.DoINeedToBeRecalculated(control, Evaluation.EquCheckType.OnlyDefinitions))
                //{
                //    flag = true;
                //}
                controlArray[i] = control;
                for(int j = 0;j<controlArray.Length;j++)
                {
                    BlockControl dbc = controlArray[i] as BlockControl;
                    if(dbc != null && dbc.MathModel != null)
                        foreach (Matan.ConnectedBlock b in dbc.MathModel.OutputBlocks)
                        {
                            b.Block.InputBlocks.RemoveAll(bc => bc.Block == dbc.MathModel);
                        }
                }
                

                this.controls.RemoveAt(controlsIndeces[i]);
                for (int j = this.connectors.Count-1; j >=0 ; j--)
                {
                    if (this.connectors[j].CE1.control == control || this.connectors[j].CE2.control == control)
                    {
                        Rectangle rc2 = this.connectors[j].ClipRectangle;
                        this.connectors[j].Dispose();
                        this.connectors.RemoveAt(j);
                        base.Invalidate(rc2);
                    }
                }
                base.Invalidate(rc);
            }
            //this.UndoRedoManager(controlArray, UnReDoType.ControlRemove, -1);
            this.controls.Sort(delegate(BaseControl a, BaseControl b)
                                     {
                                         if ((a.Location.Y < b.Location.Y) ||
                                             ((a.Location.Y == b.Location.Y) && (a.Location.X < b.Location.X)))
                                             return -1;
                                         else return 1;
                                     });
            this.current = -1;
            if (!this.redcrossvisible)
            {
                this.MousePlace = new Point(rc.X + this.Xbar.Value, rc.Y + this.Ybar.Value);
                base.Invalidate(new Rectangle(this.MousePlace.X, this.MousePlace.Y, this.gridSize, this.gridSize));
            }
            this.SelectControls(SelectionType.Testing);
            if (flag)
            {
                this.ReCalc(controlsIndeces[0]);
            }
            this.CanvasResizer();
        }

        private void RemoveConnectors(int[] connectorsIndeces)
        {
            Rectangle rc;
            for (int i = connectorsIndeces.Length - 1; i >= 0; i--)
            {
                Connector conn = this.connectors[connectorsIndeces[i]];
                rc = conn.ClipRectangle;
                rc.X -= this.Xbar.Value;
                rc.Y -= this.Ybar.Value;
                rc = Rectangle.Union(rc, new Rectangle(conn.CE1.control.Location.X - this.Xbar.Value, conn.CE1.control.Location.Y - this.Ybar.Value, conn.CE1.control.Size.Width, conn.CE1.control.Size.Height));
                rc = Rectangle.Union(rc, new Rectangle(conn.CE2.control.Location.X - this.Xbar.Value, conn.CE2.control.Location.Y - this.Ybar.Value, conn.CE2.control.Size.Width, conn.CE2.control.Size.Height));
                conn.Dispose();
                this.connectors.RemoveAt(connectorsIndeces[i]);
                base.Invalidate(rc);
            }
            //this.UndoRedoManager(controlArray, UnReDoType.ControlRemove, -1);
            this.CanvasResizer();
        }

        private int s2c(char value)
        {
            switch (value.ToString().ToLower())
            {
                case "a":
                    return 10;

                case "b":
                    return 11;

                case "c":
                    return 12;

                case "d":
                    return 13;

                case "e":
                    return 14;

                case "f":
                    return 15;
            }
            return Convert.ToInt16(value.ToString());
        }

        public bool SaveToXMCD(Stream stream)
        {
            int num = 0;
            XmlTextWriter w = new XmlTextWriter(stream, Encoding.UTF8);
            w.Formatting = Formatting.Indented;
            w.WriteStartDocument(true);
            XmlDocument doc = new XmlDocument();
            string xml = "<worksheet version=\"3.0.3\" xmlns=\"http://schemas.mathsoft.com/worksheet30\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:ws=\"http://schemas.mathsoft.com/worksheet30\" xmlns:ml=\"http://schemas.mathsoft.com/math30\" xmlns:u=\"http://schemas.mathsoft.com/units10\" xmlns:p=\"http://schemas.mathsoft.com/provenance10\"><settings><presentation><textRendering><textStyles><textStyle name=\"Normal\"><blockAttr margin-left=\"0\" margin-right=\"0\" text-indent=\"inherit\" text-align=\"left\" list-style-type=\"inherit\" tabs=\"inherit\"/><inlineAttr font-family=\"Arial\" font-charset=\"0\" font-size=\"10\" font-weight=\"normal\" font-style=\"normal\" underline=\"false\" line-through=\"false\" vertical-align=\"baseline\"/></textStyle></textStyles></textRendering><mathRendering equation-color=\"#000\"><operators multiplication=\"narrow-dot\" derivative=\"derivative\" literal-subscript=\"large\" definition=\"colon-equal\" global-definition=\"triple-equal\" local-definition=\"left-arrow\" equality=\"bold-equal\" symbolic-evaluation=\"right-arrow\"/><mathStyles><mathStyle name=\"Variables\" font-family=\"Times New Roman\" font-charset=\"0\" font-size=\"10\" font-weight=\"normal\" font-style=\"normal\" underline=\"false\"/><mathStyle name=\"Constants\" font-family=\"Times New Roman\" font-charset=\"0\" font-size=\"10\" font-weight=\"normal\" font-style=\"normal\" underline=\"false\"/><mathStyle name=\"User 1\" font-family=\"Arial\" font-charset=\"0\" font-size=\"10\" font-weight=\"normal\" font-style=\"normal\" underline=\"false\"/><mathStyle name=\"User 2\" font-family=\"Courier New\" font-charset=\"0\" font-size=\"10\" font-weight=\"normal\" font-style=\"normal\" underline=\"false\"/><mathStyle name=\"User 3\" font-family=\"Arial\" font-charset=\"0\" font-size=\"10\" font-weight=\"bold\" font-style=\"normal\" underline=\"false\"/><mathStyle name=\"User 4\" font-family=\"Times New Roman\" font-charset=\"0\" font-size=\"10\" font-weight=\"normal\" font-style=\"italic\" underline=\"false\"/><mathStyle name=\"User 5\" font-family=\"Times New Roman\" font-charset=\"0\" font-size=\"10\" font-weight=\"normal\" font-style=\"normal\" underline=\"false\"/><mathStyle name=\"User 6\" font-family=\"Arial\" font-charset=\"0\" font-size=\"10\" font-weight=\"normal\" font-style=\"normal\" underline=\"false\"/><mathStyle name=\"User 7\" font-family=\"Times New Roman\" font-charset=\"0\" font-size=\"10\" font-weight=\"normal\" font-style=\"normal\" underline=\"false\"/><mathStyle name=\"Math Text Font\" font-family=\"Times New Roman\" font-charset=\"0\" font-size=\"14\" font-weight=\"normal\" font-style=\"normal\" underline=\"false\"/></mathStyles><dimensionNames mass=\"mass\" length=\"length\" time=\"time\" current=\"current\" thermodynamic-temperature=\"temperature\" luminous-intensity=\"luminosity\" amount-of-substance=\"substance\" display=\"false\"/><symbolics derivation-steps-style=\"vertical-insert\" show-comments=\"false\" evaluate-in-place=\"false\"/><results numeric-only=\"true\"><general precision=\"3\" show-trailing-zeros=\"false\" radix=\"dec\" complex-threshold=\"10\" zero-threshold=\"15\" imaginary-value=\"i\" exponential-threshold=\"3\"/><matrix display-style=\"auto\" expand-nested-arrays=\"false\"/><unit format-units=\"true\" simplify-units=\"true\" fractional-unit-exponent=\"false\"/></results></mathRendering><pageModel show-page-frame=\"false\" show-header-frame=\"false\" show-footer-frame=\"false\" header-footer-start-page=\"1\" paper-code=\"9\" orientation=\"portrait\" print-single-page-width=\"false\" page-width=\"595.5\" page-height=\"841.5\"><margins left=\"86.4\" right=\"86.4\" top=\"86.4\" bottom=\"86.4\"/><header use-full-page-width=\"false\"/><footer use-full-page-width=\"false\"/></pageModel><colorModel background-color=\"#fff\" default-highlight-color=\"#ffff80\"/><language math=\"en\" UI=\"en\"/></presentation><calculation><builtInVariables array-origin=\"0\" convergence-tolerance=\"0.001\" constraint-tolerance=\"0.001\" random-seed=\"1\" prn-precision=\"4\" prn-col-width=\"8\"/><calculationBehavior automatic-recalculation=\"true\" matrix-strict-singularity-check=\"true\" optimize-expressions=\"false\" exact-boolean=\"true\" strings-use-origin=\"false\" zero-over-zero=\"0\"><compatibility multiple-assignment=\"MC12\" local-assignment=\"MC12\"/></calculationBehavior><units><currentUnitSystem name=\"si\" customized=\"false\"/></units></calculation><editor view-annotations=\"false\" view-regions=\"false\"><ruler is-visible=\"false\" ruler-unit=\"cm\"/><grid granularity-x=\"6\" granularity-y=\"6\"/></editor><fileFormat image-type=\"none\" image-quality=\"75\" save-numeric-results=\"true\" exclude-large-results=\"false\" save-text-images=\"false\" screen-dpi=\"96\"/><miscellaneous><handbook handbook-region-tag-ub=\"1\" can-delete-original-handbook-regions=\"true\" can-delete-user-regions=\"true\" can-print=\"true\" can-copy=\"true\" can-save=\"true\" file-permission-mask=\"4294967295\"/></miscellaneous></settings><regions></regions></worksheet>";
            doc.LoadXml(xml);
            int num2 = 0;
            /*for (int i = 1; num2 < this.controls.Count; i++)
            {
                if (this.controls[num2] is AreaControl)
                {
                    i += 2;
                }
                bool flag = false;
                if (this.controls[num2].BackColor.ToArgb() != SystemColors.Window.ToArgb())
                {
                    flag = true;
                }
                XmlElement node = doc.CreateElement("region", this.uri1);
                this.CreateXMLAttribute("region-id", i.ToString(), doc, node);
                this.CreateXMLAttribute("left", ((int) ((this.controls[num2].Location.X + (this.gridSize / 2)) / 1.28)).ToString(), doc, node);
                this.CreateXMLAttribute("top", (((int) (((double) this.controls[num2].Location.Y) / 1.28)) + (this.controls[num2].Size.Height / 2)).ToString(), doc, node);
                this.CreateXMLAttribute("width", this.controls[num2].Size.Width.ToString(), doc, node);
                this.CreateXMLAttribute("height", this.controls[num2].Size.Height.ToString(), doc, node);
                this.CreateXMLAttribute("align-x", ((int) (((double) this.controls[num2].Location.X) / 1.28)).ToString(), doc, node);
                this.CreateXMLAttribute("align-y", (((int) (((double) this.controls[num2].Location.Y) / 1.28)) + (this.controls[num2].Size.Height / 2)).ToString(), doc, node);
                this.CreateXMLAttribute("show-border", this.controls[num2].Border.ToString().ToLower(), doc, node);
                this.CreateXMLAttribute("show-highlight", flag.ToString().ToLower(), doc, node);
                this.CreateXMLAttribute("is-protected", "true", doc, node);
                this.CreateXMLAttribute("z-order", "0", doc, node);
                this.CreateXMLAttribute("background-color", flag ? this.Color2String(this.controls[num2].BackColor.ToArgb()) : "inherit", doc, node);
                this.CreateXMLAttribute("tag", "", doc, node);
                if (this.controls[num2] is MathControl)
                {
                    try
                    {
                        XmlElement element2 = doc.CreateElement("math", this.uri1);
                        this.CreateXMLAttribute("optimize", "false", doc, element2);
                        bool flag3 = !((MathControl) this.controls[num2]).Evaluate;
                        this.CreateXMLAttribute("disable-calc", flag3.ToString().ToLower(), doc, element2);
                        EquImage[] iMG = ((MathControl) this.controls[num2]).IMG;
                        EquImage[] imageArray2 = new EquImage[iMG.Length];
                        for (int j = imageArray2.Length - 1; j >= 0; j--)
                        {
                            imageArray2[j] = new EquImage(iMG[j]);
                        }
                        for (int k = imageArray2.Length - 1; k >= 0; k--)
                        {
                            if (imageArray2[k].Type == EquType.Function)
                            {
                                if (LangSelection.Type_ISO != 1)
                                {
                                    for (int m = 0; m < LangSelection.FunctionName.Length; m++)
                                    {
                                        if (imageArray2[k].Text == Function.Lg)
                                        {
                                            imageArray2[k].Text = Function.Log;
                                        }
                                        else if (imageArray2[k].Text == LangSelection.FunctionName[m])
                                        {
                                            imageArray2[k].Text = LangSelection.TypeWORLD[m];
                                        }
                                    }
                                }
                                if (imageArray2[k].Text == Function.Gamma)
                                {
                                    imageArray2[k].Text = "Γ";
                                }
                                else if (imageArray2[k].Text == Function.Nthroot)
                                {
                                    int num7;
                                    OPZAlg[] algArray = OPZAlg.Localizer(imageArray2, k, out num7);
                                    if (algArray.Length == 2)
                                    {
                                        for (int n = algArray.Length - 1; n >= 0; n--)
                                        {
                                            for (int num9 = 0; num9 < algArray[n].arr.Length; num9++)
                                            {
                                                imageArray2[k - num7--] = algArray[n].arr[num9];
                                            }
                                        }
                                    }
                                }
                                else if (imageArray2[k].Text == Function.Mat)
                                {
                                    int num10;
                                    OPZAlg[] algArray2 = OPZAlg.Localizer(imageArray2, k, out num10);
                                    Convert.ToInt32(algArray2[algArray2.Length - 2].arr[0].Text);
                                    int num11 = Convert.ToInt32(algArray2[algArray2.Length - 1].arr[0].Text);
                                    int index = 0;
                                    int num13 = 1;
                                    int num14 = algArray2.Length - 2;
                                    while (index < num14)
                                    {
                                        for (int num15 = 0; num15 < algArray2[index].arr.Length; num15++)
                                        {
                                            imageArray2[k - num10--] = algArray2[index].arr[num15];
                                        }
                                        index += num11;
                                        if (index >= num14)
                                        {
                                            index = num13++;
                                        }
                                        if (num13 > num11)
                                        {
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                        EquImage[] ei = PostfixToPrefix(imageArray2);
                        this.currentPos = -1;
                        this.RecurseFill(ei, 1, element2, doc);
                        node.AppendChild(element2);
                        goto Label_0871;
                    }
                    catch
                    {
                        num++;
                        goto Label_0884;
                    }
                }
                if (this.controls[num2] is TextControl)
                {
                    XmlElement element3 = doc.CreateElement("text", this.uri1);
                    this.CreateXMLAttribute("use-page-width", "false", doc, element3);
                    this.CreateXMLAttribute("push-down", "false", doc, element3);
                    this.CreateXMLAttribute("lock-width", "false", doc, element3);
                    XmlElement element4 = doc.CreateElement("p", this.uri1);
                    this.CreateXMLAttribute("style", "Normal", doc, element4);
                    this.CreateXMLAttribute("margin-left", "inherit", doc, element4);
                    this.CreateXMLAttribute("margin-right", "inherit", doc, element4);
                    this.CreateXMLAttribute("text-indent", "inherit", doc, element4);
                    this.CreateXMLAttribute("text-align", "inherit", doc, element4);
                    this.CreateXMLAttribute("list-style-type", "inherit", doc, element4);
                    this.CreateXMLAttribute("tabs", "inherit", doc, element4);
                    element4.InnerText = ((TextControl) this.controls[num2]).Text;
                    element3.AppendChild(element4);
                    node.AppendChild(element3);
                }
                else if (this.controls[num2] is AreaControl)
                {
                    XmlElement element5 = doc.CreateElement("area", this.uri1);
                    this.CreateXMLAttribute("is-collapsed", "true", doc, element5);
                    this.CreateXMLAttribute("name", "", doc, element5);
                    this.CreateXMLAttribute("show-name", "false", doc, element5);
                    this.CreateXMLAttribute("show-border", "true", doc, element5);
                    this.CreateXMLAttribute("show-icon", "false", doc, element5);
                    this.CreateXMLAttribute("show-timestamp", "true", doc, element5);
                    this.CreateXMLAttribute("allow-expand", "false", doc, element5);
                    this.CreateXMLAttribute("is-locked", "false", doc, element5);
                    this.CreateXMLAttribute("timestamp", "", doc, element5);
                    this.CreateXMLAttribute("top-lock-id", (i - 2).ToString(), doc, element5);
                    this.CreateXMLAttribute("bottom-lock-id", (i - 1).ToString(), doc, element5);
                    node.AppendChild(element5);
                }
                else
                {
                    num++;
                    goto Label_0884;
                }
            Label_0871:*/
                //doc.SelectSingleNode("/*/*[last()]").AppendChild(node);
            /*Label_0884:
                num2++;
            }*/
            doc.Save(w);
            w.Flush();
            if (num > 0)
            {
                //MessageBox.Show(string.Format(SSException.GetErrorText(Error.XMCDFileCanNotBeFullySaved), num.ToString()), LangSelection.FTitle);
                return false;
            }
            return true;
        }

        public bool SaveToXMCD(string fileName)
        {
            bool flag;
            try
            {
                Cursor.Current = Cursors.WaitCursor;
                using (FileStream stream = new FileStream(fileName, FileMode.Create))
                {
                    if (this.SaveToXMCD(stream))
                    {
                        //this.edited = this.UnReDoPoint;
                    }
                }
                flag = true;
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message, GlobalParams.FTitle);
                flag = false;
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
            return flag;
        }

        public void SaveToXML(Stream stream, bool outside)
        {
            XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8);
            /*writer.Formatting = Formatting.Indented;
            writer.WriteStartDocument(true);
            writer.WriteProcessingInstruction("application", "progid=\"" + LangSelection.FTitle + "\" version=\"" + LangSelection.FVersion + "\"");
            writer.WriteStartElement("regions");
            if (outside)
            {
                writer.WriteStartElement("settings");
                bool flag = this.pageState != CanvasEditStatus.ReadOnly;
                writer.WriteElementString("editable", flag.ToString().ToLower());
                for (int i = LangSelection.Languages.GetLength(0) - 1; i >= 0; i--)
                {
                    string key = LangSelection.Languages[i, 0];
                    if (this.canvasInfo.ContainsKey(key))
                    {
                        CanvasInfo info = (CanvasInfo) this.canvasInfo[key];
                        writer.WriteStartElement("metadata");
                        writer.WriteAttributeString("lang", key.ToLower());
                        writer.WriteElementString("title", info.Title);
                        writer.WriteElementString("author", info.Author);
                        writer.WriteElementString("description", info.Description);
                        writer.WriteElementString("company", info.Company);
                        writer.WriteElementString("keywords", info.Keywords);
                        writer.WriteEndElement();
                    }
                }
                writer.WriteStartElement("calculation");
                writer.WriteElementString("functions", LangSelection.Type_ISO.ToString());
                writer.WriteElementString("precision", LangSelection.num_ISO.ToString());
                writer.WriteElementString("angle", (LangSelection.corner_ISO == CornerType.Deg) ? "degrees" : "radians");
                writer.WriteElementString("fractions", (LangSelection.fraction_ISO == FractionType.Auto) ? "auto" : ((LangSelection.fraction_ISO == FractionType.Fraction) ? "fraction" : "decimal"));
                writer.WriteElementString("recalculation", LangSelection.autoReCalc.ToString().ToLower());
                writer.WriteEndElement();
                writer.WriteEndElement();
            }
            Point point = new Point(0, 0);
            if (!outside)
            {
                if (this.selected_controls.Count > 0)
                {
                    point = new Point(0x7fffffff, 0x7fffffff);
                }
                for (int j = 0; j < this.selected_controls.Count; j++)
                {
                    if (this.controls[this.selected_controls[j]].Location.X < point.X)
                    {
                        point.X = this.controls[this.selected_controls[j]].Location.X;
                    }
                    if (this.controls[this.selected_controls[j]].Location.Y < point.Y)
                    {
                        point.Y = this.controls[this.selected_controls[j]].Location.Y;
                    }
                }
            }
            int num3 = 0;
            int num4 = 0;
            while (num3 < this.controls.Count)
            {
                if (outside || this.controls[num3].Selected)
                {
                    CommonControl control = this.controls[num3];
                    writer.WriteStartElement("region");
                    writer.WriteAttributeString("id", Convert.ToString(num4++));
                    writer.WriteAttributeString("left", Convert.ToString((int) ((control.Location.X - point.X) / this.ctrlSize)));
                    writer.WriteAttributeString("top", Convert.ToString((int) ((control.Location.Y - point.Y) / this.ctrlSize)));
                    writer.WriteAttributeString("width", Convert.ToString((int) (control.Size.Width / this.ctrlSize)));
                    if (control is PlotControl)
                    {
                        writer.WriteAttributeString("height", Convert.ToString((int) (((control.Size.Height - ((PlotControl) control).math.Size.Height) + 5) / this.ctrlSize)));
                    }
                    else
                    {
                        writer.WriteAttributeString("height", Convert.ToString((int) (control.Size.Height / this.ctrlSize)));
                    }
                    writer.WriteAttributeString("border", control.Border.ToString().ToLower());
                    writer.WriteAttributeString("color", this.Color2String(control.TextColor.ToArgb()));
                    writer.WriteAttributeString("background-color", this.Color2String(control.BackColor.ToArgb()));
                    if ((control is MathControl) || (control is PlotControl))
                    {
                        EquImage[] iMG;
                        writer.WriteAttributeString("font-size", control.FontHeight.ToString());
                        if (control is MathControl)
                        {
                            iMG = ((MathControl) control).IMG;
                            writer.WriteStartElement("math");
                            switch (((MathControl) control).fraction_type)
                            {
                                case FractionType.None:
                                    writer.WriteAttributeString("fraction-type", "none");
                                    break;

                                case FractionType.Fraction:
                                    writer.WriteAttributeString("fraction-type", "fraction");
                                    break;

                                case FractionType.Auto:
                                    writer.WriteAttributeString("fraction-type", "auto");
                                    break;
                            }
                            writer.WriteAttributeString("evaluate", ((MathControl) control).Evaluate.ToString().ToLower());
                            if (control.errorId != Error.NoError)
                            {
                                writer.WriteAttributeString("error", ((int) control.errorId).ToString());
                            }
                        }
                        else
                        {
                            iMG = ((PlotControl) control).math.IMG;
                            writer.WriteStartElement("plot");
                            PlotControl control2 = (PlotControl) control;
                            switch (control2.PType)
                            {
                                case PlotType.Plot2D:
                                    writer.WriteAttributeString("type", "2d");
                                    break;

                                case PlotType.Plot3D:
                                    writer.WriteAttributeString("type", "3d");
                                    break;
                            }
                            switch (control2.RType)
                            {
                                case RenderType.Points:
                                    writer.WriteAttributeString("render", "points");
                                    break;

                                case RenderType.Lines:
                                    writer.WriteAttributeString("render", "lines");
                                    break;
                            }
                            writer.WriteAttributeString("scale_x", ((PlotControl) control).ren.scale_x.ToString());
                            writer.WriteAttributeString("scale_y", ((PlotControl) control).ren.scale_y.ToString());
                            writer.WriteAttributeString("scale_z", ((PlotControl) control).ren.scale_z.ToString());
                            writer.WriteAttributeString("rotate_x", ((PlotControl) control).ren.rotate_x.ToString());
                            writer.WriteAttributeString("rotate_y", ((PlotControl) control).ren.rotate_y.ToString());
                            writer.WriteAttributeString("rotate_z", ((PlotControl) control).ren.rotate_z.ToString());
                            writer.WriteAttributeString("transpose_x", ((PlotControl) control).ren.transpose_x.ToString());
                            writer.WriteAttributeString("transpose_y", ((PlotControl) control).ren.transpose_y.ToString());
                            writer.WriteAttributeString("transpose_z", ((PlotControl) control).ren.transpose_z.ToString());
                            writer.WriteAttributeString("evaluate", ((PlotControl) control).Evaluate.ToString().ToLower());
                            if (control.errorId != Error.NoError)
                            {
                                writer.WriteAttributeString("error", ((int) control.errorId).ToString());
                            }
                        }
                        for (int k = 0; k < iMG.Length; k++)
                        {
                            writer.WriteStartElement("e");
                            switch (iMG[k].Type)
                            {
                                case EquType.Function:
                                    writer.WriteAttributeString("type", "function");
                                    writer.WriteAttributeString("args", iMG[k].ChildCount.ToString());
                                    break;

                                case EquType.Operand:
                                    writer.WriteAttributeString("type", "operand");
                                    break;

                                case EquType.Operator:
                                    writer.WriteAttributeString("type", "operator");
                                    writer.WriteAttributeString("args", iMG[k].ChildCount.ToString());
                                    break;

                                case EquType.Bracket:
                                    writer.WriteAttributeString("type", "bracket");
                                    break;
                            }
                            writer.WriteString(iMG[k].Text);
                            writer.WriteEndElement();
                        }
                        writer.WriteEndElement();
                    }
                    else if (control is TextControl)
                    {
                        writer.WriteAttributeString("font-size", control.FontHeight.ToString());
                        TextControl control3 = (TextControl) control;
                        for (int m = LangSelection.Languages.GetLength(0) - 1; m >= 0; m--)
                        {
                            string text = control3.GetText(LangSelection.Languages[m, 0]);
                            if (!string.IsNullOrEmpty(text))
                            {
                                writer.WriteStartElement("text");
                                writer.WriteAttributeString("lang", LangSelection.Languages[m, 0].ToLower());
                                writer.WriteStartElement("p");
                                writer.WriteAttributeString("bold", control3.bold.ToString().ToLower());
                                writer.WriteAttributeString("href", control3.link.ToString());
                                writer.WriteString(text);
                                writer.WriteEndElement();
                                writer.WriteEndElement();
                            }
                        }
                    }
                    else if (control is AreaControl)
                    {
                        writer.WriteStartElement("area");
                        writer.WriteAttributeString("single", "true");
                        writer.WriteAttributeString("is-collapsed", "true");
                        writer.WriteAttributeString("name", "");
                        writer.WriteAttributeString("show-name", "false");
                        writer.WriteEndElement();
                    }
                    else if (control is PictureControl)
                    {
                        writer.WriteStartElement("picture");
                        writer.WriteStartElement("raw");
                        writer.WriteAttributeString("format", "png");
                        MemoryStream stream2 = new MemoryStream();
                        ((PictureControl) control).ExportImage().Save(stream2, ImageFormat.Png);
                        byte[] buffer = stream2.ToArray();
                        writer.WriteBinHex(buffer, 0, buffer.Length);
                        writer.WriteEndElement();
                        writer.WriteEndElement();
                    }
                    writer.WriteEndElement();
                }
                num3++;
            }
            writer.WriteEndElement();
            writer.Flush();*/
        }

        public bool SaveToXML(string fileName, bool outside)
        {
            bool flag;
            try
            {
                Cursor.Current = Cursors.WaitCursor;
                using (FileStream stream = new FileStream(fileName, FileMode.Create))
                {
                    this.SaveToXML(stream, outside);
                }
                if (outside)
                {
                    //this.edited = this.UnReDoPoint;
                }
                flag = true;
            }
            catch (Exception exception)
            {
                //MessageBox.Show(exception.Message, LangSelection.FTitle);
                flag = false;
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
            return flag;
        }

        private void ScrollBars_ValueChanged(object sender, EventArgs e)
        {
            this.Xbar.Value = this.Grider(this.Xbar.Value);
            this.Ybar.Value = this.Grider(this.Ybar.Value);
            if ((this.xBar != this.Xbar.Value) || (this.yBar != this.Ybar.Value))
            {
                this.curElt = new Rectangle();
                base.Invalidate(new Rectangle(0, 0, this.SheetSize.Width, this.SheetSize.Height));
            }
            this.xBar = this.Xbar.Value;
            this.yBar = this.Ybar.Value;
        }

        private void ScrollControlToScreenBoundsSmooth(BaseControl value)
        {
            int num = (value.Location.X - this.Xbar.Value) + this.gridSize;
            int num2 = (value.Location.Y - this.Ybar.Value) + this.gridSize;
            if ((num + value.Size.Width) >= this.SheetSize.Width)
            {
                if (value.Size.Width >= this.SheetSize.Width)
                {
                    this.Xbar.Value = value.Location.X;
                }
                else
                {
                    this.Xbar.Value += (num + value.Size.Width) - this.SheetSize.Width;
                }
            }
            if ((num2 + value.Size.Height) >= this.SheetSize.Height)
            {
                if (value.Size.Height >= this.SheetSize.Height)
                {
                    this.Ybar.Value = value.Location.Y;
                }
                else
                {
                    this.Ybar.Value += (num2 + value.Size.Height) - this.SheetSize.Height;
                }
            }
        }

        private void select2focusTimer_Tick(object sender, EventArgs e)
        {
            this.select2focusTimer.Enabled = false;
        }

        private void SelectControls(SelectionType value)
        {
            this.selected_controls.Clear();
            for(int i = 0; i<this.controls.Count;i++)
            {
                BaseControl control = this.controls[i];
                if (value == SelectionType.ByRectangle)
                {
                    bool flag = this.rc.Left <= control.Right - this.Xbar.Value && 
                        this.rc.Right >= control.Location.X - this.Xbar.Value && 
                        this.rc.Top <= control.Bottom - this.Ybar.Value &&
                        this.rc.Bottom >= control.Location.Y - this.Ybar.Value;
                    bool flag2 = false;
                    if (this.selected_controls_ctrl.Length > 0)
                    {
                        for (int j = this.selected_controls_ctrl.Length - 1; j >= 0; j--)
                        {
                            if (this.selected_controls_ctrl[j] == i)
                            {
                                if (control.Selected == flag)
                                {
                                    control.Selected = !control.Selected;
                                }
                                flag2 = true;
                                break;
                            }
                        }
                        if (!flag2 && (control.Selected != flag))
                        {
                            control.Selected = !control.Selected;
                        }
                    }
                    else if (control.Selected != flag)
                    {
                        control.Selected = !control.Selected;
                    }
                }
                else if (value == SelectionType.All)
                {
                    control.Selected = true;
                }
                else if (value == SelectionType.None)
                {
                    control.Selected = false;
                }
                if (control.Selected)
                {
                    this.selected_controls.Add(i);
                }
            }
            Rectangle tmpRc = rc;
            tmpRc.Offset(this.Xbar.Value, this.Ybar.Value);
            for (int i = 0; i < this.connectors.Count; i++)
            {
                Connector c = this.connectors[i];
                if (value == SelectionType.ByRectangle)
                {
                    GraphicsPathIterator gpIter = new GraphicsPathIterator(c.ConnectorArea);
                    gpIter.Rewind();
                    GraphicsPath gp = new GraphicsPath();
                    bool isClosed;
                    bool flag=false;
                    while (gpIter.NextSubpath(gp, out isClosed) > 0 && !flag)
                    {
                        flag = gp.GetBounds().IntersectsWith(tmpRc);
                        gp = new GraphicsPath();
                    }
                    if (c.Selected != flag)
                    {
                        c.Selected = !c.Selected;
                        Rectangle rect = Rectangle.Ceiling(c.ConnectorArea.GetBounds());
                        rect.X -= Xbar.Value;
                        rect.Y -= Ybar.Value;
                        rect.Inflate(1, 1);
                        this.Invalidate(rect);
                    }

                }
                else if (value == SelectionType.All)
                {
                    c.Selected = true;
                }
                else if (value == SelectionType.None)
                {
                    c.Selected = false;
                }
            }
        }

        public void SetColor(Color color, int inc)
        {
            this.StartCacheHistory();
            bool flag = false;
            for (int i = this.selected_controls.Count - 1; i >= 0; i--)
            {
                switch (inc)
                {
                    case 0:
                        this.controls[this.selected_controls[i]].TextColor = color;
                        break;

                    case 1:
                        this.controls[this.selected_controls[i]].SelectedTextColor = color;
                        break;

                    case 2:
                        this.controls[this.selected_controls[i]].BackColor = color;
                        break;

                    case 3:
                        this.controls[this.selected_controls[i]].SelectedBackColor = color;
                        break;

                    case 4:
                        this.controls[this.selected_controls[i]].WarningColor = color;
                        break;
                }
                this.controls[this.selected_controls[i]].PrePainter();
                this.controls[this.selected_controls[i]].RePainter();
                flag = true;
            }
            if (!flag)
            {
                GlobalParams.clr[inc] = color;
            }
            //this.ContinueHistory(UnReDoType.Control);
        }

        /*public void SetCurrentTextLang()
        {
            for (int i = this.controls.Count - 1; i >= 0; i--)
            {
                if (this.controls[i] is TextControl)
                {
                    ((TextControl) this.controls[i]).SetCurrentText();
                }
            }
        }*/

        private void SetEvalEndValue(DateTime end)
        {
            if (this.InvokeRequired)
            {
                base.Invoke(new DoSetEvalEndValue(this.SetEvalEndValue), end);
            }
            else
            {
                //this.evalEnd = end;
            }
        }

        /*private void SetEvaluation_onShowResult(CommonControl sender, bool state)
        {
            if (this.InvokeRequired)
            {
                base.Invoke(new DoSetEvaluationOnShowResult(this.SetEvaluation_onShowResult),
                    sender, state );
            }
            else
            {
                MathControl math = null;
                if (sender is MathControl)
                {
                    math = (MathControl) sender;
                }
                else if (sender is PlotControl)
                {
                    math = ((PlotControl) sender).math;
                }
                if (math != null)
                {
                    math.InEvaluation = state;
                }
            }
        }*/

        /*public void SetEvalution(bool evalute)
        {
            this.StartCacheHistory();
            bool flag = false;
            if (this.selected_controls.Count > 0)
            {
                for (int i = this.selected_controls.Count - 1; i >= 0; i--)
                {
                    if (this.controls[this.selected_controls[i]] is MathControl)
                    {
                        MathControl control = (MathControl) this.controls[this.selected_controls[i]];
                        if (control.Evaluate != evalute)
                        {
                            control.Evaluate = evalute;
                            control.RePainter();
                            flag = true;
                        }
                    }
                    else if (this.controls[this.selected_controls[i]] is PlotControl)
                    {
                        PlotControl control2 = (PlotControl) this.controls[this.selected_controls[i]];
                        if (control2.Evaluate != evalute)
                        {
                            control2.Evaluate = evalute;
                            control2.RePainter();
                            flag = true;
                        }
                    }
                    else if ((this.controls[this.selected_controls[i]] is AreaControl) && ((AreaControl) this.controls[this.selected_controls[i]]).top)
                    {
                        AreaControl control3 = (AreaControl) this.controls[this.selected_controls[i]];
                        if (control3.Evaluate != evalute)
                        {
                            control3.Evaluate = evalute;
                            control3.RePainter();
                            flag = true;
                        }
                    }
                }
            }
            else if (this.current != -1)
            {
                if (this.controls[this.current] is MathControl)
                {
                    MathControl control4 = (MathControl) this.controls[this.current];
                    if (control4.Evaluate != evalute)
                    {
                        control4.Evaluate = evalute;
                        control4.RePainter();
                        flag = true;
                    }
                }
                else if (this.controls[this.current] is PlotControl)
                {
                    PlotControl control5 = (PlotControl) this.controls[this.current];
                    if (control5.Evaluate != evalute)
                    {
                        control5.Evaluate = evalute;
                        control5.RePainter();
                        flag = true;
                    }
                }
                else if ((this.controls[this.current] is AreaControl) && ((AreaControl) this.controls[this.current]).top)
                {
                    AreaControl control6 = (AreaControl) this.controls[this.current];
                    if (control6.Evaluate != evalute)
                    {
                        control6.Evaluate = evalute;
                        control6.RePainter();
                        flag = true;
                    }
                }
            }
            if (flag)
            {
                this.ReCalc((this.selected_controls.Count > 0) ? this.selected_controls[0] : this.current);
            }
            this.ContinueHistory(UnReDoType.Control);
        }*/

        private int SetInputInControl(Point point, bool start)
        {
            for (int i = 0; i < this.controls.Count; i++)
            {
                if (this.controls[i].Location.X <= point.X &&
                    (this.controls[i].Right - this.gridSize / 2 >= point.X) &&
                    (this.controls[i].Location.Y + this.gridSize / 2 <= point.Y) &&
                    (this.controls[i].Bottom - this.gridSize / 2 >= point.Y))
                {
                    int num5;
                    int num6;
                    this.current = i;
                    int num3 = ((this.controls[this.current].Location.X - this.Xbar.Value) + this.gridSize / 2) + 1;
                    int num4 = ((this.controls[this.current].Location.Y - this.Ybar.Value) + this.gridSize / 2) + 1;
                    if (!start)
                    {
                        num5 = ((this.controls[this.current].Right - this.Xbar.Value) - this.gridSize / 2) - 1;
                        num6 = ((this.controls[this.current].Bottom - this.Ybar.Value) - this.gridSize / 2) - 1;
                    }
                    else
                    {
                        num5 = num3;
                        num6 = num4;
                    }
                    this.OnMouseDown(new MouseEventArgs(MouseButtons.Left, 1, num5, num6, 0));
                    this.OnMouseUp(new MouseEventArgs(MouseButtons.Left, 1, num5, num6, 0));
                    if (this.current != -1)
                    {
                        if ((num3 < 0) || ((num3 + this.controls[this.current].Size.Width) > this.SheetSize.Width))
                        {
                            this.Xbar.Value += num3;
                        }
                        if ((num4 < 0) || ((num4 + this.controls[this.current].Size.Height) > this.SheetSize.Height))
                        {
                            this.Ybar.Value += num4;
                        }
                        return i;
                    }
                }
            }
            return -1;
        }

        /*public void SetLang(string lang)
        {
            for (int i = this.selected_controls.Count - 1; i >= 0; i--)
            {
                if (this.controls[this.selected_controls[i]] is TextControl)
                {
                    ((TextControl) this.controls[this.selected_controls[i]]).ShowText(lang);
                    this.controls[this.selected_controls[i]].PrePainter();
                    this.controls[this.selected_controls[i]].RePainter();
                }
            }
            if (((this.selected_controls.Count == 0) && (this.current != -1)) && ((this.current < this.controls.Count) && (this.controls[this.current] is TextControl)))
            {
                ((TextControl) this.controls[this.current]).ShowText(lang);
            }
        }*/

        public void SetSize(int inc)
        {
            this.StartCacheHistory();
            bool flag = false;
            for (int i = this.selected_controls.Count - 1; i >= 0; i--)
            {
                this.controls[this.selected_controls[i]].FontHeight = inc;
                this.controls[this.selected_controls[i]].PrePainter();
                this.controls[this.selected_controls[i]].RePainter();
                flag = true;
            }
            if (!flag)
            {
                GlobalParams.fontsize_ISO = inc;
            }
            //this.ContinueHistory(UnReDoType.Control);
        }

        private void ShiftY(int Vertical, int TopStart)
        {
            this.StartCacheHistory();
            Vertical = this.Grider(Vertical);
            for (int i = this.controls.Count - 1; i >= 0; i--)
            {
                if (this.controls[i].Location.Y < TopStart)
                {
                    break;
                }
                this.controls[i].Location = new Point(this.controls[i].Location.X, this.controls[i].Location.Y + Vertical);
            }
            //this.ContinueHistory(UnReDoType.Control);
        }

        private void smartDec_Tick(object sender, EventArgs e)
        {
            //this.smartDec.Enabled = false;
        }

        private void SmartInputUnDo()
        {
            //if ((this.current != -1) && (this.controls[this.current].UnDo() == null))
            //{
            //    this.controls[this.current].UnReInit();
            //}
        }

        private void smartTimer_Tick(object sender, EventArgs e)
        {
            //this.smartTimer.Enabled = false;
            this.StartCacheHistory();
        }

        private void StartCacheHistory()
        {
            if (this.cacheControls == null)
            {
                this.cacheControls = new List<BaseControl>();
            }
            this.cacheStatus = true;
        }

        private void StartLocationChanging()
        {
            //this.hash = this.controls.GetHash();
        }

        private void StopHistory()
        {
            this.cacheControls = null;
            this.cacheStatus = true;
        }

        /*private bool StopLocationChanging(bool recalc, CommonControl start, int prevIndex)
        {
            //this.controls.Sort();
            bool flag = false;
            //if (recalc && (this.hash != this.controls.GetHash()))
            //{
            //    this.ReCalc(Math.Min(prevIndex, this.controls.IndexOf(start)));
            //    flag = true;
            //}
            //this.hash = null;
            return flag;
        }*/

        private int String2Color(string value)
        {
            value = value.TrimStart(new char[] { '#' });
            return Color.FromArgb((this.s2c(value[0]) * 0x10) + this.s2c(value[1]), (this.s2c(value[2]) * 0x10) + this.s2c(value[3]), (this.s2c(value[4]) * 0x10) + this.s2c(value[5])).ToArgb();
        }

        /*private void sur_paint(PaintEventArgs e)
        {
            if (this.sur_random == null)
            {
                this.sur_brush = null;
                this.sur_brushG = new SolidBrush(Color.DarkGreen);
                this.sur_brushB = new SolidBrush(Color.Black);
                this.sur_brushR = new SolidBrush(Color.Red);
                this.sur_brushY = new SolidBrush(Color.Yellow);
                this.sur_random = new Random();
            }
            for (int i = 0; i < (this.CanvasSize.Width + this.gridSize); i += this.gridSize)
            {
                if ((((((this.sur_y == (this.gridSize * 4)) && (i == (this.gridSize * 4))) || ((this.sur_y == (this.gridSize * 4)) && (i == (this.gridSize * 8)))) || (((this.sur_y == (this.gridSize * 5)) && (i == (this.gridSize * 3))) || ((this.sur_y == (this.gridSize * 5)) && (i == (this.gridSize * 5))))) || ((((this.sur_y == (this.gridSize * 5)) && (i == (this.gridSize * 7))) || ((this.sur_y == (this.gridSize * 5)) && (i == (this.gridSize * 9)))) || (((this.sur_y == (this.gridSize * 6)) && (i == (this.gridSize * 4))) || ((this.sur_y == (this.gridSize * 6)) && (i == (this.gridSize * 8)))))) || (((((this.sur_y == (this.gridSize * 8)) && (i == (this.gridSize * 3))) || ((this.sur_y == (this.gridSize * 8)) && (i == (this.gridSize * 9)))) || (((this.sur_y == (this.gridSize * 9)) && (i == (this.gridSize * 4))) || ((this.sur_y == (this.gridSize * 9)) && (i == (this.gridSize * 8))))) || ((((this.sur_y == (this.gridSize * 10)) && (i == (this.gridSize * 5))) || ((this.sur_y == (this.gridSize * 10)) && (i == (this.gridSize * 6)))) || ((this.sur_y == (this.gridSize * 10)) && (i == (this.gridSize * 7))))))
                {
                    this.sur_brush = this.sur_brushR;
                }
                else if ((((this.sur_y != (this.gridSize * 3)) || ((i != (this.gridSize * 2)) && (i != (this.gridSize * 10)))) && ((this.sur_y != (this.gridSize * 11)) || ((i != (this.gridSize * 2)) && (i != (this.gridSize * 10))))) && (((this.sur_y >= (this.gridSize * 3)) && (this.sur_y <= (this.gridSize * 11))) && ((i >= (this.gridSize * 2)) && (i <= (this.gridSize * 10)))))
                {
                    this.sur_brush = this.sur_brushY;
                }
                else if (this.sur_random.Next(2) == 0)
                {
                    this.sur_brush = this.sur_brushG;
                }
                else
                {
                    this.sur_brush = this.sur_brushB;
                }
                e.Graphics.FillRectangle(this.sur_brush, new Rectangle(i, e.ClipRectangle.Y, i + this.gridSize, e.ClipRectangle.Height));
            }
        }*/

        /*private void sur_timer_Tick(object sender, EventArgs e)
        {
            if (this.sur_y > this.CanvasSize.Height)
            {
                this.sur_y = 0;
            }
            base.Invalidate(new Rectangle(0, this.sur_y, this.CanvasSize.Width, this.gridSize));
            this.sur_y += this.gridSize;
        }*/

        private string ToGreek(char value)
        {
            char ch;
            bool flag = char.IsLower(value);
            if (value == 'J')
            {
                return "ϑ";
            }
            if (value == 'ϑ')
            {
                return "J";
            }
            value = value.ToString().ToLower()[0];
            switch (value)
            {
                case 'a':
                    ch = 'α';
                    break;

                case 'b':
                    ch = 'β';
                    break;

                case 'c':
                    ch = 'χ';
                    break;

                case 'd':
                    ch = 'δ';
                    break;

                case 'e':
                    ch = 'ε';
                    break;

                case 'f':
                    ch = 'φ';
                    break;

                case 'g':
                    ch = 'γ';
                    break;

                case 'h':
                    ch = 'η';
                    break;

                case 'i':
                    ch = 'ι';
                    break;

                case 'j':
                    ch = 'ϕ';
                    break;

                case 'k':
                    ch = 'κ';
                    break;

                case 'l':
                    ch = 'λ';
                    break;

                case 'm':
                    ch = 'μ';
                    break;

                case 'n':
                    ch = 'ν';
                    break;

                case 'o':
                    ch = 'ο';
                    break;

                case 'p':
                    ch = 'π';
                    break;

                case 'q':
                    ch = 'θ';
                    break;

                case 'r':
                    ch = 'ρ';
                    break;

                case 's':
                    ch = 'σ';
                    break;

                case 't':
                    ch = 'τ';
                    break;

                case 'u':
                    ch = 'υ';
                    break;

                case 'v':
                    ch = 'ϖ';
                    break;

                case 'w':
                    ch = 'ω';
                    break;

                case 'x':
                    ch = 'ξ';
                    break;

                case 'y':
                    ch = 'ψ';
                    break;

                case 'z':
                    ch = 'ζ';
                    break;

                case 'α':
                    ch = 'a';
                    break;

                case 'β':
                    ch = 'b';
                    break;

                case 'γ':
                    ch = 'g';
                    break;

                case 'δ':
                    ch = 'd';
                    break;

                case 'ε':
                    ch = 'e';
                    break;

                case 'ζ':
                    ch = 'z';
                    break;

                case 'η':
                    ch = 'h';
                    break;

                case 'θ':
                    ch = 'q';
                    break;

                case 'ι':
                    ch = 'i';
                    break;

                case 'κ':
                    ch = 'k';
                    break;

                case 'λ':
                    ch = 'l';
                    break;

                case 'μ':
                    ch = 'm';
                    break;

                case 'ν':
                    ch = 'n';
                    break;

                case 'ξ':
                    ch = 'x';
                    break;

                case 'ο':
                    ch = 'o';
                    break;

                case 'π':
                    ch = 'p';
                    break;

                case 'ρ':
                    ch = 'r';
                    break;

                case 'σ':
                    ch = 's';
                    break;

                case 'τ':
                    ch = 't';
                    break;

                case 'υ':
                    ch = 'u';
                    break;

                case 'φ':
                    ch = 'f';
                    break;

                case 'χ':
                    ch = 'c';
                    break;

                case 'ψ':
                    ch = 'y';
                    break;

                case 'ω':
                    ch = 'w';
                    break;

                case 'ϕ':
                    ch = 'j';
                    break;

                case 'ϖ':
                    ch = 'v';
                    break;

                default:
                    return value.ToString();
            }
            if (!flag)
            {
                return ch.ToString().ToUpper();
            }
            return ch.ToString();
        }

        public void UnDo()
        {
            /*if ((this.UnReDoPoint >= 0) && (this.UnReDO.Count > this.UnReDoPoint))
            {
                this.UnReFocusSetter(this.UnReDO[this.UnReDoPoint].current);
                if (this.UnReDO[this.UnReDoPoint].type == UnReDoType.Control)
                {
                    this.UnReStateControl(true);
                }
                else if (this.UnReDO[this.UnReDoPoint].type == UnReDoType.ControlAdd)
                {
                    this.UnReRemoveControls();
                }
                else if (this.UnReDO[this.UnReDoPoint].type == UnReDoType.ControlRemove)
                {
                    this.UnReAddControls();
                }
                this.UnReDoPoint--;
            }*/
        }

        /*private void UndoRedoManager(CommonControl[] control, UnReDoType type, int current)
        {
            if (this.cacheStatus)
            {
                if (this.cacheControls != null)
                {
                    for (int i = control.Length - 1; i >= 0; i--)
                    {
                        int num2 = this.cacheControls.Count - 1;
                        while ((num2 >= 0) && (this.cacheControls[num2] != control[i]))
                        {
                            num2--;
                        }
                        if (num2 == -1)
                        {
                            this.cacheControls.Add(control[i]);
                        }
                    }
                }
            }
            else
            {
                if (this.UnReDoMaximum != this.UnReDoPoint)
                {
                    this.UnReDO.RemoveRange(this.UnReDoPoint + 1, (this.UnReDO.Count - this.UnReDoPoint) - 1);
                }
                this.UnReDoPoint++;
                this.UnReDoMaximum = this.UnReDoPoint;
                this.UnReDO.Add(new UnReDO_Canvas(control, current, type));
            }
        }*/

        /*private void UndoRedoManager(CommonControl control, UnReDoType type, int current)
        {
            this.UndoRedoManager(new CommonControl[] { control }, type, current);
        }*/

        private void UnReAddControls()
        {
            /*bool flag = false;
            this.controls.AddRange(this.UnReDO[this.UnReDoPoint].controls);
            CommonControl control = null;
            for (int i = this.UnReDO[this.UnReDoPoint].controls.Length - 1; i >= 0; i--)
            {
                control = this.UnReDO[this.UnReDoPoint].controls[i];
                control.Focused = false;
                control.Selected = false;
                control.RePainter();
                if (!flag && Evaluation.DoINeedToBeRecalculated(control, Evaluation.EquCheckType.EqualsAndDefinitions))
                {
                    flag = true;
                }
            }
            this.controls.Sort();
            if (control != null)
            {
                int index = this.controls.IndexOf(control);
                if (flag && (index != -1))
                {
                    this.ReCalc(index);
                }
            }*/
        }

        private void UnReFocusSetter(int index)
        {
            /*if (index >= this.controls.Count)
            {
                index = -1;
            }
            if (this.current == -1)
            {
                this.DeleteRedCross();
            }
            else
            {
                base.Invalidate(new Rectangle(this.MousePlace.X, this.MousePlace.Y, this.gridSize, this.gridSize));
            }
            this.current = index;
            for (int i = this.controls.Count - 1; i >= 0; i--)
            {
                if (this.current == i)
                {
                    if (!this.controls[i].Focused)
                    {
                        this.controls[i].Focused = true;
                        int num2 = (this.controls[this.current].Location.X - this.Xbar.Value) + 1;
                        int num3 = (this.controls[this.current].Location.Y - this.Ybar.Value) + 1;
                        if ((num2 < 0) || ((num2 + this.controls[this.current].Size.Width) > this.CanvasSize.Width))
                        {
                            this.Xbar.Value += num2;
                        }
                        if ((num3 < 0) || ((num3 + this.controls[this.current].Size.Height) > this.CanvasSize.Height))
                        {
                            this.Ybar.Value += num3;
                        }
                    }
                }
                else if (this.controls[i].Focused)
                {
                    this.controls[i].Focused = false;
                    this.controls[i].RePainter();
                }
            }
            if (this.current != -1)
            {
                this.controls[this.current].RePainter();
            }*/
        }

        private void UnReRemoveControls()
        {
            /*bool flag = false;
            Rectangle rc = new Rectangle();
            int startIndex = -1;
            CommonControl control = null;
            for (int i = this.UnReDO[this.UnReDoPoint].controls.Length - 1; i >= 0; i--)
            {
                control = this.UnReDO[this.UnReDoPoint].controls[i];
                rc = new Rectangle(control.Location.X - this.Xbar.Value, control.Location.Y - this.Ybar.Value, control.Size.Width, control.Size.Height);
                if (!flag && Evaluation.DoINeedToBeRecalculated(control, Evaluation.EquCheckType.OnlyDefinitions))
                {
                    flag = true;
                }
                startIndex = this.controls.Remove(control);
                base.Invalidate(rc);
            }
            this.controls.Sort();
            this.current = -1;
            if (!this.redcrossvisible)
            {
                this.MousePlace = new Point(rc.X + this.Xbar.Value, rc.Y + this.Ybar.Value);
                base.Invalidate(new Rectangle(this.MousePlace.X, this.MousePlace.Y, this.gridSize, this.gridSize));
            }
            this.SelectControls(SelectionType.Testing);
            if (flag && (startIndex != -1))
            {
                this.ReCalc(startIndex);
            }
            this.CanvasResizer();*/
        }

        private void UnReStateControl(bool undo)
        {
           /* this.StartLocationChanging();
            bool recalc = false;
            CommonControl control = null;
            for (int i = this.UnReDO[this.UnReDoPoint].controls.Length - 1; i >= 0; i--)
            {
                control = this.UnReDO[this.UnReDoPoint].controls[i];
                Point location = control.Location;
                UnReDO_Common common = undo ? control.UnDo() : control.ReDo();
                if ((((common != null) && !(control is PlotControl)) && ((common is UnReDO_MathMemory) || (location != control.Location))) && (!recalc && Evaluation.DoINeedToBeRecalculated(control, Evaluation.EquCheckType.EqualsAndDefinitions)))
                {
                    recalc = true;
                }
            }
            int index = this.controls.IndexOf(control);
            if (!this.StopLocationChanging(recalc, control, index) && recalc)
            {
                this.ReCalc(index);
            }*/
        }

        /*private void v_CalculateMe(CalculateType e, CommonControl sender)
        {
            if (this.InvokeRequired)
            {
                DoVCalculateMe method = new DoVCalculateMe(this.v_CalculateMe);
                base.Invoke(method, new object[] { e, sender });
            }
            else if (this.current != -1)
            {
                if (sender is PlotControl)
                {
                    int index = this.controls.IndexOf(sender);
                    this.ReCalc(index, index);
                }
                else if ((sender is MathControl) && (e != CalculateType.Ending))
                {
                    MathControl control = (MathControl) sender;
                    EquImage[] iMG = control.IMG;
                    if (Evaluation.DoINeedToBeRecalculated(control, Evaluation.EquCheckType.OnlyDefinitions))
                    {
                        this.ReCalc(this.controls.IndexOf(sender));
                    }
                    else
                    {
                        if ((iMG[iMG.Length - 1].Text == "=") || (iMG[iMG.Length - 1].Text == "—"))
                        {
                            iMG = OPZAlg.Localizer(control.IMG, control.IMG.Length - 1)[0].arr;
                        }
                        control.Action(iMG, new EquImage[] { new EquImage("#", EquType.Operand, 0) }, e);
                        int startIndex = this.controls.IndexOf(sender);
                        this.ReCalc(startIndex, startIndex);
                    }
                }
                if (e == CalculateType.Ending)
                {
                    bool inDate = sender.InDate;
                    if (!sender.InDate && Evaluation.DoINeedToBeRecalculated(sender, Evaluation.EquCheckType.EqualsAndDefinitions))
                    {
                        this.ReCalc(this.controls.IndexOf(sender));
                    }
                    if ((inDate == sender.InDate) || ((((MathControl) sender).error == -1) && (((MathControl) sender).ErrorText == "")))
                    {
                        this.ControlUnfocus();
                    }
                }
            }
        }*/

        /*private void v_errorprovider(Exception e, int Position, EquImage value, CommonControl sender)
        {
            if (this.InvokeRequired)
            {
                ELERRORPROVGUI method = new ELERRORPROVGUI(this.v_errorprovider);
                base.Invoke(method, new object[] { e, Position, value, sender });
            }
            else
            {
                MathControl math = null;
                if (sender is MathControl)
                {
                    math = (MathControl) sender;
                }
                else if (sender is PlotControl)
                {
                    math = ((PlotControl) sender).math;
                }
                math.InEvaluation = false;
                sender.InDate = true;
                sender.ErrorText = e.Message;
                sender.errorId = SSException.GetErrorId(e);
                if ((Position > -1) && (math.IMG.Length > Position))
                {
                    EquImage image = math.IMG[Position];
                    if (((image.Text == value.Text) && (image.ChildCount == value.ChildCount)) && (image.Type == value.Type))
                    {
                        math.error = Position;
                        sender.RePainter();
                    }
                }
                if ((math != null) && math.Focused)
                {
                    this.DoErrorDisplay(sender.ErrorText, new Point(sender.Location.X + 2, sender.Bottom), true);
                }
                if (Position == -2)
                {
                    sender.ErrorText = "";
                }
            }
        }*/

        /*private void v_history(CommonControl sender)
        {
            if (this.InvokeRequired)
            {
                ELHISTORYGUI method = new ELHISTORYGUI(this.v_history);
                base.Invoke(method, new object[] { sender });
            }
            else
            {
                this.UndoRedoManager(sender, UnReDoType.Control, this.current);
            }
        }*/

        /*private void v_OnLinkClick(CommonControl sender)
        {
            if (this.InvokeRequired)
            {
                ELLINKCLICKGUI method = new ELLINKCLICKGUI(this.v_OnLinkClick);
                base.Invoke(method, new object[] { sender });
            }
            else if (sender is TextControl)
            {
                this.LinkOpener(((TextControl) sender).link);
            }
        }*/

        private void control_OnResize(BaseControl sender)
        {
            this.CanvasResizer(sender);
        }

        private void control_Repainting(BaseControl sender, Rectangle e)
        {

            this.curElt = e;
            Rectangle rect = new Rectangle(e.X - this.xBar, (e.Y - (sender.Focused ? this.currentDelta : this.AreaCommonDelta(sender))) - this.yBar, e.Width, e.Height);
            this.DoSetCANVASUpdate(rect);

        }

        private void connector_Repainting(Connector sender, Rectangle e)
        {
            this.curElt = e;
            Rectangle rect = new Rectangle(e.X - this.xBar, e.Y  - this.yBar, e.Width, e.Height);
            this.DoSetCANVASUpdate(rect);
        }

        /*private void v1_collapsedChanged(CommonControl sender, bool collapsed)
        {
            base.Invalidate();
        }*/

        public List<BaseControl> CanvasControls
        {
            get
            {
                return this.controls;
            }
        }

        public Size SheetSize
        {
            get
            {
                return new Size(this.Width - GlobalParams.ScrollBarWidth, this.Height - GlobalParams.ScrollBarWidth);
            }
        }

        public Size SheetAreaSize
        {
            get
            {
                return new Size(this.Width + this.Xbar.Maximum - GlobalParams.ScrollBarWidth,
                    this.Height + this.Ybar.Maximum - GlobalParams.ScrollBarWidth);
            }
        }

        public bool Edited
        {
            get
            {
                return this.edited!=0; //!= this.UnReDoPoint;
            }
        }

        /*public bool IsEvalutionInProgress
        {
            get
            {
                return (this.evalThread != null);
            }
        }*/
        
        public bool IsSelected
        {
            get
            {
                return ((this.selected_controls != null) && (this.selected_controls.Count > 0));
            }
        }

        private Point MousePlace
        {
            get
            {
                return this.mousePlace;
            }
            set
            {
                this.mousePlace = value;
                if ((((this.current == -1) && (base.Width > this.gridSize)) && ((base.Height > this.gridSize) && (this.Ybar != null))) && (this.Xbar != null))
                {
                    if ((this.mousePlace.X + this.gridSize) > ((base.Width - this.Ybar.Width) + this.Xbar.Value))
                    {
                        this.Xbar.Value += this.Grider((this.mousePlace.X + (2 * this.gridSize)) - ((base.Width - this.Ybar.Width) + this.Xbar.Value));
                    }
                    if ((this.mousePlace.Y + this.gridSize) > ((base.Height - this.Xbar.Height) + this.Ybar.Value))
                    {
                        this.Ybar.Value += this.Grider((this.mousePlace.Y + (2 * this.gridSize)) - ((base.Height - this.Xbar.Height) + this.Ybar.Value));
                    }
                    if (this.mousePlace.X < this.Xbar.Value)
                    {
                        this.Xbar.Value += this.Grider(this.mousePlace.X - this.Xbar.Value);
                    }
                    if (this.mousePlace.Y < this.Ybar.Value)
                    {
                        this.Ybar.Value += this.Grider(this.mousePlace.Y - this.Ybar.Value);
                    }
                }
            }
        }

        /*private int UnReDoPoint
        {
            get
            {
                return this.unReDoPoint;
            }
            set
            {
                this.unReDoPoint = value;
                if ((this.unReDoPoint > -1) && (this.unReDoPoint < this.UnReDoMaximum))
                {
                    this.unReDoStatus = UnReDoStatus.FullHistory;
                }
                else if (this.unReDoPoint > -1)
                {
                    this.unReDoStatus = UnReDoStatus.NoForward;
                }
                else if ((this.UnReDoMaximum > 0) && (this.unReDoPoint < this.UnReDoMaximum))
                {
                    this.unReDoStatus = UnReDoStatus.NoBack;
                }
                else
                {
                    this.unReDoStatus = UnReDoStatus.NoHistory;
                }
            }
        }*/

        //public delegate void DelegateDoPrepareError(Exception e, MathControl v, EquImage[] ei, ParamWizard param, CalculateType value);

        //public delegate void DoEvaluationOnShowResult(MathControl sender, EquImage[] ei, EquImage[] tstr2, CalculateType value);

        public delegate void DoSetEvalEndValue(DateTime end);

        //public delegate void DoSetEvaluationOnShowResult(CommonControl sender, bool state);

        //public delegate void DoVCalculateMe(CalculateType e, CommonControl sender);

        //public delegate void ELERRORPROVGUI(Exception e, int Position, EquImage value, CommonControl sender);

        //public delegate void ELHISTORYGUI(CommonControl sender);

        //public delegate void ELLINKCLICKGUI(CommonControl sender);

        //public delegate void ELREPAINTERGUI(CommonControl sender, Rectangle e);

        private enum SelectionType
        {
            ByRectangle,
            All,
            None,
            Testing
        }

        public delegate void BarGUI(int max);

        public delegate void SheetGUI(Rectangle rect);

    }

    public enum ClipboardStatus
    {
        Empty,
        HasData
    }

    public enum CanvasEditStatus
    {
        Editable,
        ReadOnly,
        Calculation
    }

    public enum CursorType
    {
        Default,
        Arrow,
        Text,
        Move,
        Moving,
        MovingAdd,
        SizeH,
        SizeV,
        SizeNWSE
    }

    public class CursorStatus
    {
        private int control;
        private CursorType cursorType;

        public CursorStatus(int control, CursorType cursorType)
        {
            this.control = control;
            this.cursorType = this.CursorType;
        }

        public int Control
        {
            get
            {
                return this.control;
            }
            set
            {
                this.control = value;
            }
        }

        public CursorType CursorType
        {
            get
            {
                return this.cursorType;
            }
            set
            {
                this.cursorType = value;
            }
        }
    }
}

